1

I am writing my first ever Shell script today. I think I have found everything I need online but need help on one thing:

I want to be able to pass a couple of optional arguments when the script is called: e.g myscript.sh -filename somefilename -location some/file/location -deleteoption yes

all them 3 options are optional so I need my script at the very first stage to loop through each argument and then depending on the descriptor of the argument (e.g -filename) store the value (somefilename) in to the correct variable?

another thing is that the options can be given in any order.

How do I go about achieving this functionality?

2
  • 1
    shell is not a shell, it would be worthwhile to figure out whether you're using bash, zsh, csh , tcsh, ash, ksh , dash or any of the other literally infinite (though only in a figurative sense) number of shells available. Commented Jan 6, 2012 at 14:09
  • For bash, possible duplicate of stackoverflow.com/questions/255898/… Commented Apr 9, 2013 at 1:51

4 Answers 4

2

If you're using bash, you might want to use getopts. Otherwise, googling for "shellname option parsing" should return something similar for your shell of choice.

Sign up to request clarification or add additional context in comments.

Comments

1

In BASH/SH:

while [ $# -gt 0]
do

  # parse arguments, arguments are in $1 TO $9

  shift

done

Comments

0

If you mean bash then here's an identical question with some good answers:

How to iterate over arguments in a Bash script

Comments

0

One approach is to pass things in the environment instead of using getopts to parse the arguments. For example:

$ cat my-script
#!/bin/sh
echo filename is ${filename-undefined}

$ ./my-script
filename is undefined
$ filename=foo ./my-script
filename is foo

One drawback to this approach is that any subshells will have filename defined in their environment. This is normally not a problem, but if it is you can certainly get it out of the environment with:

#!/bin/sh
f=$filename
unset filename
filename=$f

A bigger problem is that the program cannot validate the names. For example, if the user invokes:

$ filname=foo ./my-script

there is no way for my-script to notice the error. If you parse the arguments, the script can emit an error about "unknown option 'filname'" and the user will notice the typo. Passing the value in the environment makes it impossible to do such a check.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.