Last Updated: December 24, 2019
·
4.516K
· pmaoui

Bash/Shell script quick cheat sheet

I don't create enough bash scripts to keep in mind everything. You'll find below what I need to get back in business :

 How to declare a function :

my_function() {
    mkdir $1
}

How to call a function with a condition :

[ $zero -eq 0 ] && { my_function "directoryname" ; }

Get the current folder of the current script :

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

Get the dereferenced path (all directory symlinks resolved), do this:

DIR="$( cd -P "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

Get the return code of a script :

command param
STATUS_CODE=$?
[ $STATUS_CODE -eq 0 ] && echo "Ok it has worked"
[ $STATUS_CODE -ne 0 ] && echo "Ouch, something bad happened"

Just an other way to write this (but you can do things on several lines) :

[ $STATUS_CODE -eq 0 ] && { 
echo "Ok it has worked"
} || {
echo "Ouch, something bad happened"
 }

Variable testing :

if [ -z $X ]; then
    echo "the variable X is empty"
fi

[ -s $file_path ] && echo "the file exists and is not empty"

 Careful : an empty string return true with -s, you should use -z

[ -z $X ] ||  echo "not empty"

[ -z $X ] &&  echo "empty" || echo "not empty"

Remove * except file :

rm !(file) 
rm !(file1|file2)

For loop

for file in `ls`
do
    echo file
done

Iterative loop

for VARIABLE in 1 2 3 4 5 .. N
do
    command1
    command2
    commandN
done

Remove or replace a string

ok = "smting.mp3"
echo ${ok//.mp3} #return "somting"

Read a file line by line

while read line
        do
                command "${line}"
        done < file.xt