Bash Cheat Sheet

Here’s my bash cheat sheet:

Tests

Combining

[ condition ] && action; # action executes if condition is true.
[ condition ] || action; # action executes if condition is false.

Filesystem related tests

We can test different filesystem related attributes using different condition flags as follows:

[ -f $file_var ]: Returns true if the given variable holds a regular filepath or filename.
[ -x $var ]: Returns true if the given variable holds a file path or filename which is executable.
[ -d $var ]: Returns true if the given variable holds a directory path or directory name.
[ -e $var ]: Returns true if the given variable holds an existing file.
[ -c $var ]: Returns true if the given variable holds path of a character device file.
[ -b $var ]: Returns true if the given variable holds path of a block device file.
[ -w $var ]: Returns true if the given variable holds path of a file which is writable.
[ -r $var ]: Returns true if the given variable holds path of a file which is readable.
[ -L $var ]: Returns true if the given variable holds path of a symlink.

An example of the usage is as follows:

fpath="/etc/passwd"
if [ -e $fpath ]; then
echo File exists; 
else
echo Does not exist; 
fi

String comparisons

While using string comparison, it is best to use double square brackets since use of single brackets can sometimes lead to errors. Usage of single brackets sometimes lead to error. So it is better to avoid them.

Two strings can be compared to check whether they are the same as follows;

[[ $str1 = $str2 ]]: Returns true when str1 equals str2, that is, the text contents of str1 and str2 are the same
[[ $str1 == $str2 ]]: It is alternative method for string equality check

We can check whether two strings are not the same as follows:

[[ $str1 != $str2 ]]: Returns true when str1 and str2 mismatches

We can find out the alphabetically smaller or larger string as follows:

[[ $str1 > $str2 ]]: Returns true when str1 is alphabetically greater than str2
[[ $str1 < $str2 ]]: Returns true when str1 is alphabetically lesser than str2

Note that a space is provided after and before =. If space is not provided, it is not a comparison, but it becomes an assignment statement.

[[ -z $str1 ]]: Returns true if str1 holds an empty string
[[ -n $str1 ]]: Returns true if str1 holds a non-empty string

It is easier to combine multiple conditions using the logical operators && and || as follows:

if [[ -n $str1 ]] && [[ -z $str2 ]] ;
then
commands;
fi

For example:

str1="Not empty "
str2=""
if [[ -n $str1 ]] && [[ -z $str2 ]];
then
echo str1 is non-empty and str2 is empty string.
fi

The output is as follows:

str1 is non-empty and str2 is empty string.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.