0

Is there a way to pass more than one option when running a script?

My script has this case:

case "$1" in
 b)
 backup_start $1
 ;;

 h)
 _usage
 ;;

 *)
 echo 'Invalid option, -h for help'
 ;;
esac

I run my script with:

myscript -b backupname

But sometimes I would like to run the script with an option with another argument...that I will then use in case inside the script:

myscript -b backupname -t mynewarg
7
  • ok, but now your getops-using code only cares about t, not about b. And you don't use MYINTERNALENV anywhere, and you still don't cite where you have this code from. Commented Mar 9 at 20:22
  • I apologize again but the script that I have to create is still in the initial phase. I’m trying to be able to create a script that accepts at least two parameters when it is launched: -b = backup_name -t = backup_type i've updated my post. Commented Mar 9 at 20:31
  • does your distro include /usr/share/doc/util-linux/examples/getopt-example.bash example? you should read that Commented Mar 9 at 20:33
  • first thing I see is that when you handle -b xxxx you only shift rather than shift 2 since -b takes a supplementary argument Commented Mar 9 at 20:35
  • 3
    well, you have this tagged getopts, and I'm pretty sure there are posts with that tag containing examples of how to use getopts, so that might be a place to start... Commented Mar 9 at 20:46

2 Answers 2

2

The way to do it is to use a loop until getopts can process no more arguments:

while getopts "b:t:h" option; do
case $option in

 t)
 export MYINTERNALENV="$OPTARG"
 ;;

 b)
 backup_start "$OPTARG"
 ;;

 h)
 _usage
 ;;

 ?)
 echo 'Invalid option, -h for help'
 ;;

 esac
done
-6

I suggest:

case "$1" in
  -h|--help)
    _usage
    exit
    ;;
esac

backup_start $@
5
  • hm, how does that allow OP to specify both -t arg and -b arg at the same time? Commented Mar 9 at 20:07
  • @MarcusMüller: I've updated my answer. Commented Mar 9 at 20:09
  • Sorry, that doesn't improve the situation? How are you addressing OP's question? Commented Mar 9 at 20:10
  • @MarcusMüller: All args passed to backup_start with $@. Commented Mar 9 at 20:10
  • but that's not what OP wants to do. The question is about handling arguments passed to this script (myscript), not to hand them off to another script (backup_start). Commented Mar 9 at 20:12

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.