Bash Scripting Examples: Basic Information and Control Structures

Last updated:
Table of Contents

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 [ ])

Preferred 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
    # or do this 

If then else using grep matches

Does $PATH include "some_string"?

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

If not

Spaces are important!

if [[ ! condition ]];then
    # do stuff
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 > file_name << EOF 
$variables are expanded
more text

To disable variable expansion inside the text block, use quotes around the delimiter:

cat > file_name << "EOF" 
$no $variable expansion performed
more text

TROUBLESHOOTING error: delimited by end-of-file (wanted `EOF'): Make sure you have no other characters after EOF

Check whether a string matches a regular expression

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

Simplest possible function definition

function do_something {
    echo "this gets printed to standard output"

# to call it, just use its name

Function with parameters

It's the same thing as the item above (acessing command-line arguments): $1 is the first parameter, $2 is the second one, etc etc.

function say_something {
    echo "$1"
$ say_something "foobar"
# prints "foobar"
$ say_something
# prints nothing
$ say_something foo bar
# prints "foo" (other arguments weren't accessed)

Check the number of parameters passed to a function

$# returns the number of parmeters passed

    if [[ $# -eq 0 ]]; then
      # no parameters passed
    elif [[ $# -eq 1 ]]; then
      # 1 parameter passed
      # 2 or more parameters passed

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"
  echo "no virtualenv" 

Dialogue & Discussion