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:

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:


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

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


# 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
# Now we can ask a new question
read -p "What is your favorite food?"

# And again we copy the answer to a new variable

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

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

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

# The && symbol means "and"

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