Bash
Bash Programming
whereis bash
The first line indicates the system which program to use to run the file. Use whereis bash
to see where bash is.
Redirection
&
&
indicates that what follows is a file descriptor and not a file name.
File descriptor
stdin
stdout
: File descriptor1
is the standard output (stdout
).stderr
: File descriptor2
is the standard error (stderr
).
Examples
ls -l > ls.txt
:This will redirect
stdout
of a program (ls -l
) to a file (ls.txt
).grep da * 2> grep-errors.txt
This will redirect the
stderr
(2
) of a program (grep da *
) to a file (grep-errors.txt
).grep da * 2>&1
This will redirect the
stderr
(2
) of a program (grep da *
) to be written to thestdout
(1
).grep da * 2>1
This will redirect the
stderr
(2
) of a program (grep da *
) to a file (1
).ls -l > ls.log 2>&1
This will redirect
stdout
of a program (ls -l
) to a file (ls.log
) and redirectstderr
(2
) tostdout
(1
).ls -l &> ls.log
This is equivalent to
ls -l > ls.log 2>&1
.ls -l &> ls.log &
This is equivalent to
ls -l &> ls.log
, but running in a "subshell". If the current shell is closed, the "subshell" would be closed as well.nohup ls -l > ls.log &
This is equivalent to
ls -l &> ls.log &
, but running separately. Closing the current shell would not terminate the program.nohup ls -l &
This is equivalent to
nohup ls -l > ls.log &
, but the output is written intonohup.out
file in the current folder.grep da * > /dev/null
This will redirect
stdout
of a program (grep da *
) to the null device.grep da * &> /dev/null
This will redirect
stdout
andstderr
of a program (grep da *
) to the null device.
Pipes
Pipes let you use the output of a program as the input of another one.
Examples
ls -l | sed -e "s/[aeio]/u/g"
Here, the following happens: first the command
ls -l
is executed, and it's output, instead of being printed, is sent (piped) to thesed
program, which in turn, prints what it has to.
Variables
No type, no declaration.
Local variables
Local variables can be created by using the keyword local
.
Conditionals
if..then
if..then...else
Conditionals with variables
Loop
For
While
Util
Functions
Without paramerters
With paramerters
User interfaces
Menus
Command line
-z
: the length of STRING is zero. Please check man test
.
Return value
The return value (status) of a command is stored in the $?
variable.
The return value is called exit status. This value can be used to determine whether a command completed successfully or unsuccessfully. If the command exits successfully, the exit status will be zero, otherwise it will be a nonzero value.
The following script reports the success/failure status of a command: