Wednesday, December 26, 2007

Simple Command Line Arguments in BASH

The number of arguments in the command line in BASH scripts is stored in $#, while the list of arguments is stored in $@. You can access arguments by there index. For example, $1 is the first argument in the list and $2 is the second ... etc. Notice that $0 is the name of the file (script file name)

Code example (documentation is left as an exercise for the reader)

--------------------------------------------------------------------
#!/bin/bash
# This code will mv not executable (-x flag is off)
# from src_dir(def=".") to target_dir.

src_dir=''
target_dir=''

if [ -z "$1" ]; then
echo "Usage: `basename $0` [src_dir] target_dir
exit
fi

if [ "$#" == 2 ]; then
if [ ! -d "$1" -o ! -d "$2" ]; then
echo "Error: You must supply directory names on the cmd line"
exit
fi
src_dir=$1
target_dir=$2
else
src_dir="."
target_dir=$1
fi

for file in $src_dir/*
do
if [ ! -x $file ]; then
mv $file $target_dir
fi
done
--------------------------------------------------------------------

No comments: