Shell Script

From Wiki Notes @ WuJiewen.com, by Jiewen Wu
Jump to: navigation, search

Introduction

Shell accepts user's instructions or commands and if they are valid, they can be passed to kernel. Shell, as a command language interpreter, is not part of system kernel, but uses the system kernel to execute programs, create files etc.


There are several Shell variants, like BASH, CSH, TCSH, KSH. To know what your current system shell is, type:

> echo $SHELL

To run a Shell script, try any of the following (you may need to change the permission of the script first):

> chmod 755 foo.sh
> bash foo.sh
> sh foo.sh
> ./foo.sh

Options for executing scripts, -v print shell input lines as they are read. -x: expanding the values of system variables.

Variables

Always use echo $var to get the system variable's value:

BASH;BASH_VERSION;COLUMNS;HOME;
LINES;LOGNAME;OSTYPE;PATH;
PS1;PWD;SHELL;USERNAME

User defined variables(a value of "" or empty means NULL):

> myvar = 10
> echo -e "defined \n $myvar"

Note that echo has the option -e for interpretation of the following backslash escaped characters in the strings:

\a alert (bell)
\b backspace
\c suppress trailing new line
\n new line
\r carriage return
\t horizontal tab
\\ backslash

Special Varaibles

  • $? prints the exit status of commands.
  • $$ PID of shell
  • $# number of command line arguments
  • $* all arguments to shell
  • $@ all arguments to shell
  • $- option supplied to shell
  • $! PID of last started background process (started with &)

N.B. PID is in the range 0-65536.

Arithmetic, Quotes, Wild Cards

Use back quote (` is for command) only, and leave spaces around operators.

> echo `expr 1 + 2`

Double quotes (") remove the meaning of characters except \ and $, e.g., output variables. Single quotes (') retain the meaning of everything.

> echo "$myvar" : you get 10
> echo '$myvar' : you get $myvar
> echo `date`   : you get the current date

Wild cards can be used for filename shorthand or meta characters.

  • * matches any string/any number of chars
  • ? matches any single char
  • [] matches any of the enclosed chars
  • More wild cards are defined in Regular Expression.
> ls /bin/[!c-e];exit

Input & Output

Use read to receive inputs.

> read -t 3 myvar

The -t option for read followed by a number of seconds provides an automatic timeout for read. The -s option hides the user's typing.

For the above command, $0 refers to the shell script name, i.e., read, $1 for myvar. $# is 1, and $* expands to `$1`.

> redirects to a file (overwritten), and >> redirects to a file (append). < takes as input a file instead of stdin. | is a pipe, which connects the output of one program to the input of another. We can also use filters to process intermediate contents, e.g., uniq.

> sort < sourcefile | uniq > sorted_file

Conditionals & Loops

Operators

For maths, we can use both sets of ops.

-eq[==]  -ne[!=]  -lt[<]  -le[<=]  -gt[>]  -ge[>=]

For strings, use the following.

=   !=   str (undefined or not null)  
-n str (exists and not null)   -z str (exists and null) 

For files and dirs,

-s (nonempty)  -f(file?)  -d(dir?)  -r/x/w(permissions allowed?)

Logical ops,

! -a(and) -o(or)

Syntax

if [cond];
then 
...(cond is true if 1 or the exit status of commands is 0)
else
fi

Multilevel ifs.

if [cond];
then 
elif [cond];
then  ...
else  ...
fi


For loops,

for  var  in listofitems  
//also, for ((expr1; expr2; expr3))
do ...
done

While loops,

while [cond]
do ...
done

Case loops,

case $var in 
pattern1) ...;;
pattern2) ...;;
*) ...;;
esac

Note that test or expr can be used to evaluate the conditions. OR can be used among expressions, e.g., test cond1 OR cond2.

References