Difference between revisions of "Shell Script"

From Wiki Notes @ WuJiewen.com, by Jiewen Wu
Jump to: navigation, search
(Input & Output)
(Input & Output)
Line 63: Line 63:
 
Use ''read'' to receive inputs.
 
Use ''read'' to receive inputs.
 
  > read myvar
 
  > read myvar
The -t option for read followed by a number of seconds provides an automatic timeout for read.
+
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 ''read'', $1 for myvar.
 
For the above command, $0 refers to ''read'', $1 for myvar.

Revision as of 22:02, 27 January 2009

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
  • [] 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 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 read, $1 for myvar.