Bash:ScriptExamples

From wiki
Jump to navigation Jump to search


Control structures

if conditions then [[ block ]] else [[ block ]] fi
Generic if statement

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

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