Bash Basics

Mon, Mar 15, 2010 One-minute read

Bash is a shell scripting language included on most Linux and Mac computers. It’s useful for writing small scripts that don’t require another software language to be installed and are immediately portable. Good places to use bash scripts are when you want to write a cronjob, backup some files, or run an update task. Here are the basics to get you started.

Start your script with She-Bang header:

#!/bin/bash

Variables are assigned by a key-value pairing:

FILENAME="~/docs/input"

You can print to the console by using echo:

echo $FILENAME

An IF statement:

if [ ! -s $FILENAME ] ; then
  touch $FILENAME
fi

The bang ! negates the result, and the -s parameter checks if a file exists.

Example of a function:

function getFile
{
  # function contents here
  # the hash/pound symbol makes the rest of this line a comment
}

Call this function by using its name:

getFile

You can pass a variable to a function:

getFile "/home/user/docs/file.txt"

And use it within the function by reference to $1

function getFile
{
  echo $1
}