Bash Cheatsheet

kuniga.me > Docs > Bash Cheatsheet

Bash Cheatsheet

I really dislike working with Bash. I never get familiar with the syntax and there are a lot of idiosyncrasies and hard-to-read params. I tend to prefer using the subprocess module in Python. That said, sometimes it is incovenient to not use Bash. Assumes Bash v 3.2.

Bash can be very strict with the syntax (especially around new lines, spaces and quotes) which lead to frustrating syntax errors. I’ll add notes when syntax is important.

See shellcheck for this purpose.

Assignment

NOTES:

Example:

x=10

Conditionals

Syntax:

if [ ... ]
then
    ...
fi

NOTES:

Check if string is empty

x=""
if [ -z $x ]
then
   echo "empty"
else
    echo "not-empty"
fi

To flip the check, use -n.

NOTE:

x="hello"
if [ -n "$x" ]
then
   echo "not-empty"
else
    echo "empty"
fi

And (&&)

Syntax: [ <cond1> ] && [ <cond2> ]

x=10
if [ $x -gt 1 ] && [ $x -lt 100 ]
then
    echo "correct"
fi