A quick and simple guide to bashing about.

This article is not yet entirely complete.


A value is assigned to a variable in the following format, ( note that you should never put any blank spaces around the “=” )

  <variable name>=<value>;

So, to make a variable named name to have the value “john”:


If you want to assign the results of executed command ( command substitution ) to a variable you have to run the command in a subshell.

  list=`ls -l`;
  # OR 
  list=$( ls -l );

Now $list will contain whatever the command “ls -l” returned.


If we wanted to retrieve the variable’s value, we use $.

  # will print "John is sick" to the screen.
  echo $name is sick;

There are some specials cases for using $.

Lets say we had a file called script:


# do some stuff here;  

and we call it with:

  $ ./script A B C

If whe used $0, it would expand to the file name of the script.

  echo $0; # will print "script"

$1, or $ is the _n_th parameter passed to script when it was called.

  echo $1; # would print "A";
  echo $2; # would print "B";
  echo $3; # would print "C";

String Manipulation

There are many things we can do with strings in bash.


  echo ${#name}; # prints 6


  a=motor; b=boat;
  c=$a$b; # makes c="motorboat"
  echo $a$b; # prints "motorboat"

substring extration

  echo ${stringV:0}; # prints "abcdef"
  echo ${stringV:2}; # prints "cdef"
  # notice the space before the '-'
  echo ${stringV: -1};  prints "f"
  echo ${stringV: -2}; # prints "ef"
  echo ${stringV:0:2}; # prints "ab";

substring removal

Deletes shortest match of $substring from front of $string.


Deletes longest match of $substring from front of $string.


Number Arithmetic

Bash has built in support for doing some maths with integers.

  echo $(( 1 + 2 ));  # Addition
  echo $(( 1 - 2 ));  # Subtraction
  echo $(( 10 / 3 )); # Division
  echo $(( 10 % 3 )); # Remainder