Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash script that handles optional arguments

Tags:

bash

shell

I have a bashscript that expects an optional argument as follows, there are several things that I would like to refine it so that I can pass in the first argument in different ways(0, false to indicate a false value, all other string to indicate true, defaults to false), what's an elegant way to script this? I would like to use if statement with the right boolean expression.

if [ -n "$1" ]; then
    update_httpconf="$1";
fi
if [ "$update_httpconf" = "true" ]; then
    echo "hi";
fi
like image 760
user121196 Avatar asked Oct 22 '22 20:10

user121196


1 Answers

If you made it so that making the first argument --update-httpconf counts as true, and anything else counts as false, it would be more consistent with other unixey command line utilities.

This might be a good starting point:

while [ $# -gt 0 ]
do
    case $1 in
        '--update-httpconf')
            update_httpconf=true
            ;;
        *)
            echo "unrecognised arg $1"; exit
            ;;
    esac
    shift
done
like image 97
hdgarrood Avatar answered Oct 24 '22 17:10

hdgarrood