Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a bash script that takes arguments?

Tags:

bash

I already know about getopts, and this is fine, but it is annoying that you have to have a flag even for mandatory arguments.

Ideally, I'd like to be able to have a script which receives arguments in this form:

script.sh [optional arguments] [anything required]

for example

script.sh -rvx output_file.txt

where the script says you HAVE to have an output file. Is there any easy way to do this?

As far as I know, with getopts it would have to look like: script.sh -rvx -f output_file.txt, and that is just not very clean.

I can also use python if necessary, but only have 2.4 available, which is a bit dated.

like image 977
A Question Asker Avatar asked Jan 03 '11 18:01

A Question Asker


1 Answers

Don't use the getopts builtin, use getopt(1) instead. They are (subtly) different and do different things well. For you scenario you could do this:

#!/bin/bash

eval set -- $(getopt -n $0 -o "-rvxl:" -- "$@")

declare r v x l
declare -a files
while [ $# -gt 0 ] ; do
        case "$1" in
                -r) r=1 ; shift ;;
                -v) v=1 ; shift ;;
                -x) x=1 ; shift ;;
                -l) shift ; l="$1" ; shift ;;
                --) shift ;;
                -*) echo "bad option '$1'" ; exit 1 ;;
                *) files=("${files[@]}" "$1") ; shift ;;
         esac
done

if [ ${#files} -eq 0 ] ; then
        echo output file required
        exit 1
fi

[ ! -z "$r" ] && echo "r on"
[ ! -z "$v" ] && echo "v on"
[ ! -z "$x" ] && echo "x on"

[ ! -z "$l" ] && echo "l == $l"

echo "output file(s): ${files[@]}"

EDIT: for completeness I have provided an example of handling an option requiring an argument.

like image 137
sorpigal Avatar answered Sep 28 '22 15:09

sorpigal