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?

Léo Léopold Hertz 준영
  • 134,464
  • 179
  • 445
  • 697
Mo.
  • 40,243
  • 37
  • 86
  • 131
  • 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. – paxdiablo Jan 06 '12 at 14:09
  • For bash, possible duplicate of http://stackoverflow.com/questions/255898/how-to-iterate-over-arguments-in-bash-script – congusbongus Apr 09 '13 at 01:51

4 Answers4

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.

Frank Schmitt
  • 30,195
  • 12
  • 73
  • 107
1

In BASH/SH:

while [ $# -gt 0]
do

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

  shift

done
Mithrandir
  • 24,869
  • 6
  • 50
  • 66
0

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

How to iterate over arguments in a Bash script

Community
  • 1
  • 1
sdragnev
  • 468
  • 3
  • 10
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.

William Pursell
  • 204,365
  • 48
  • 270
  • 300