Introduction to Bash programming

Tue, 09/04/2012 - 16:59 -- jamie

Bash is a simple programming language typically used by system administrators to automate tasks.

Try creating a new file with this command:

nano my-script

Type the following into your file:

#!/bin/bash
echo "Hello World!"

Then, save and exit.

Execute your new bash script with:

bash my-script

With a Bash program (aka script) anything you type on the command line can be placed into the script. For example, try creating a bash script with the following contents:

#!/bin/bash

cd /etc
echo "Here is a listing of the /etc/ directory"
ls

In addition, bash can also request input from the user and assign the answer to a variable:

#!/bin/bash

# Any line that starts with a # is a comment and is not executed
# These lines are used to explain what the code is doing

# The read command assigns the answer to the prompt to the variable $REPLY
read -p "What is your favorite color?"

# The answer is now in the variable $REPLY. Let's copy that to a new variable
color="$REPLY"
# Now we can ask a new question
read -p "What is your favorite food?"

# And again we copy the answer to a new variable
food="$REPLY"

# -z checks if the user left the variable empty (e.g. the user just hit enter without
# typing anything)

if [ -z "$color" ]; then
  echo "You didn't provide a color."
  exit
fi

if [ -z "$food" ]; then
  echo "You didn't provide a food."
  exit
fi

# the || symbol means "or"
if [ "$color" = "green" ] || [ "$color" = "pink" ]; then
  echo "I like those colors too."
else
  echo "You like ugly colors"
fi

# The && symbol means "and"

if [ "$color" = "green" ] && [ "$food" = "ice cream" ]; then
  echo "Right on!"
fi