Thursday, September 24, 2009

Some Interesting Bash Functions

In Linux there is a type of scripting that can be done in the Bash shell.  This is a very powerful feature of Linux, as Bash offers many advanced features.  This blog will show some of the features I have learned.  I will not attempt to cover a tutorial but rather varying functions that I have found useful.

IFS
   One of the interesting things that I have learned is the usage of IFS.  According to wikipedia it stands for Internal Field Separator.  What it does is allow you to define what Bash defines as a separator.  Bash defaults to space as the separator, therefore functions that utilize IFS will separate items based on spaces.

  While scripting you might want to change this.  Maybe a comma or a new line will be what is wanted.  Here is an example that sets the value to a new line and then back to the default.


#set IFS to be a new line
IFS="
"
#set IFS to be a space
IFS=" " 

Checking Arguments
  When you are implementing a bash script you can pass in arguments to the program.  Each argument is listed as $(value) where value ranges from 0 on up.  $0 is your program, $1 is the first passed in argument, etc.

Now what we want to do is check how many the user input.  Maybe we only want 2 values to be input, so we should check that.  Here is an example that checks for 2 inputs.


if [ $# -ne 2 ]; then
  echo "You did not input 2 arguments, try again!"
  exit
fi

Iterate Through all Files in CWD
  Sometimes it is necessary to iterate through all files in a certain directory.  There are a few ways to do this, but if you are dealing with files that may have spaces in them, the best way is the following.


for file in `ls -A $src`; do 
  sourceFile="$src/$file"
  # Now do what you want it to do with each source file
done


* Note: In the above example you will note $src, this is the full length path where you are searching files.  This can be a hard coded variable or possibly an argument to your function.

* Note: Whenever you reference sourceFile make sure to use quotes

Checking for Certain Things
  When you are coding you might want to check what something is.  Here are a few ways to check.

Checking that a directory exists

if [ ! -d "$dir" ]; then
  #do something since the directory does not exist
fi

Checking for a regular file

if [ -f "$file" ]; then
  #do something since it is a normal file
fi

Checking if file1 is newer than file2

if [ "$file1" -nt "$file2" ]; then
  # file1 is newer, so do something here
fi

No comments:

Post a Comment