bash Cheat Sheet

if

if [ expression ]
        then
                commands
elif [ expression2 ]
        then
                commands
else
                commands
fi

case

case string1 in
        str1)
                commands;;
        str2)
                commands;;
        *)
                commands;;
esac

Loops

for var1 in list
do
        commands
done

for i in `seq 0 100`
do
	echo $i
done

while [ expression ]
do
        commands
done

until [ expression ]
do
        commands
done

File tests

-d filename 	  	return True if filename is a director
-f filename 	  	return True if filename is a normal file
-r filename 	  	return True if filename is readable
-s filename 	  	return True if filename is not empty
-w filename 	  	return True if filename is writable
-x filename 	  	return True if filename is executable

Test program arguments

while [ $# -gt 0 ]; do    # Until you run out of parameters . . .
	case "$1" in
	--without-lxc)
		WITH_LXC="no"
		;;
	--help)
		configure_help
		exit 0
		;;
	esac
	shift       # Check next set of parameters.
done

Test the number of script arguments

if [ $# -ne 1 ]
then
	echo "Error: program argument missing"
fi

Test grep result

grep "somestring" somefile
if [ "$?" -eq 0 ];
then
	echo "processing somefile"
fi

Test command result

some_command
if [ $? -eq 0 ]; then
        echo OK
else
        echo FAIL
fi

Test environment variable

if [ -n "${ENV_VAR+x}" ]
then
	... do something ...
else
	... do something ...
fi

Test if a program is installed

if which program >/dev/null; then
    echo program found
else
    echo program not found
    exit 1
fi

Create a “here document”

cat > lxc.conf << EOF
lxc.utsname = $1
lxc.rootfs = $1/rootfs
lxc.mount.entry=/lib lib none ro,bind 0 0
lxc.mount.entry=/bin bin none ro,bind 0 0
lxc.mount.entry=/usr usr none ro,bind 0 0
lxc.mount.entry=/sbin sbin none ro,bind 0 0
lxc.mount.entry=/lib64 lib64 none ro,bind 0 0
lxc.mount.entry=proc /proc proc nodev,noexec,nosuid 0 0
lxc.mount.entry=tmpfs /dev/shm tmpfs  defaults 0 0
lxc.pts=1024
EOF

Arithmetic

i=1
i=$[i+1]
echo $i

Some other bash resources

Defensive BASH Programming

Leave a comment