Bash Scripting Simple Usage Examples and Reference

Last updated:

In many commands, I've used [[ ]] to test conditions. Use [[ ]] unless you need to run on shells other than bash (in which case you should use [ ])

Shebang/hashbang

add this to the start of every script.

#!/usr/bin/env bash

If then, else if, else

spaces before and after [[ and before ]] are important!

if [[ condition ]];then
    # do stuff
elif [[ other condition ]]; then
    # something else
else
    # or do this 
fi

If then else using grep matches

Does $PATH include "some_string"?

if echo $PATH | grep -q "some_string"; then
    echo "matches!"
else
    echo "no matches"
fi

If not

Spaces are important!

if [[ ! condition ]];then
    # do stuff
fi;

Create an array

some_array[0]="foo"
some_array[1]="bar"
some_array[2]="baz"

Iterate through array

suppose some_array is an array like the one in the previous example. This will print the array's contents.

for i in "${some_array[@]}"; do
  echo $i
done

Iterate through a range

for i in {1..5}; do
  echo $i
done

Iterate through lines in a file

while read p; do
  echo $p
done < /path/to/some/file

Iterate through files in a directory

for f in some/path/*; do
  echo "$f"
done 

as a one-liner: for f in some/path/*; do echo "$f"; done

Split a string into an array using a delimiter

I think IFS is needed even though you are not going to use it. (The string gets split into the tokens variable.)

IFS=':' read -a tokens <<< "foo:bar:baz"

echo ${tokens[0]}
#prints "foo"

some_var=${tokens[2]}
echo $some_var
#prints "baz"
echo "text"

Access command-line arguments via special variables

$# is the number of arguments provided to the current script

$0 is the script name

$1, $2, $3 and so on until $9 are the first argument, second argument, third argument and so on.

Write a heredoc to a file

Writing multi-line strings to a file.

cat << EOF > file_name
text
more text
EOF;

Check whether a string matches a regular expression

if [[ "foo" =~ ^f ]];
then
 echo "match"
fi

Check the number of parameters passed to a function

$# returns the number of parmeters passed

myfunction(){
    if [[ $# -eq 0 ]]; then
      # no parameters passed
    elif [[ $# -eq 1 ]]; then
      # 1 parameter passed
    else
      # 2 or more parameters passed
    fi
}

Check if a command exists

For example, the program deactivate is enabled if you have an active python virtual environment.

If you wish to test whether the current user is in a virtual env, one way is to test whether the command deactivate exists, you can use the type builtin and test its result;

# piping the output of this command to dev null
# to avoid noise
ret=$(type deactivate &> /dev/null)

if [[ $? -eq 0 ]]; then
  echo "we're in a virtual env"
else
  echo "no virtualenv" 
fi

Dialogue & Discussion