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
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