Bash Examples: Basic Information and Control Structures

Bash Examples: Basic Information and Control Structures

Last updated:
Table of Contents

Shebang

add this to the start of every script.

#!/usr/bin/env bash

If then 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 with 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;

AND operator

Use &&:

a=true
b=false

if [[ $a && $b ]];then
    # will NOT print
    echo "a and b is true"
fi

OR operator

Use ||

a=true
b=false

if [[ $a || $b ]];then
    # will print
    echo "a or b is true"
fi

Access command-line arguments

$# 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.

Check if command exists

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 virtualenv, one way is to test whether the command deactivate exists, you can use the type builtin and test its result;

Example: Test if command deactivate exists in this system

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

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

Dialogue & Discussion