Little bash tip

On 30 January 2008, in computing, by ayoli

Here’s a short type to handle arguments given like this to a bash script :

./my_script -arg value

First, we test if an argument has been given :


if [ $# -eq 0 ]; then
  1. no args, we echo a short help message and exit
    echo -e “usage : ./my_script -arg [value|other_value]”
    exit 1
    fi

After, here’s the code which is going to handle the argument and its value :

if [ ”$1” = ”-arg” ]; then
shift;#we shift to the value, now $1 is the string given after -arg
case ”$1” in
“value”) echo -e ” here we do something with the value value” ;;
“other_value”) echo -e ” here we do something with the value other_value”;;
  • echo -e “default case, maybe value is missing or is not wanted value” ;;
    esac
    fi

Tagged with:  

Leave a Reply

WordPress Themes

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!