Bash:ScriptExamples
Control structures
- if
if <conditions>
then
<block>
elif <conditions>
then
<block>
else
<block>
fi
- while
while <conditions>
do
<block>
done
conditions
In the if statement a condition is true if the exit code ($?) is 0 else it is false.
So the condition can be any statement. If the statement may have output you can redirect that to /dev/null.
The test statement can be used to test variables
To have multiple conditions use && or || for and and or
while caveat
When the block contains calls to external systems (remsh, ssh) this call swallows all input and consequently the loop is ended. This can be prevented by assigning specific input to the call (e.g. ssh user@system command < /dev/null
Blocks
You can create blocks of code by putting () or {} around the commands. Can be handy to redirect all output of a block.
() creates a subshell, variables set in the subshell will not be available outside the block.
{} executes the block in the same context, variables set in the block are available outside the block too.
Check interactive shell
To check within a startup script (like .bashrc) whether or not Bash is running interactively. Test if $- has an 'i' in it or if $PS1 (the prompt) exists.
case "$-" in
*i*) echo This shell is interactive ;;
*) echo This shell is not interactive ;;
esac
if [ -z "$PS1" ]; then
echo This shell is not interactive
else
echo This shell is interactive