Shell Script
Contents
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
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 &)
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
Input & Output
Use read to receive inputs.
> read myvar,myvar2