Is there a way to feed non positional arguments to a shell script? Meaning explicitly specify some kind of flag?
. myscript.sh value1 value2
. myscript.sh -val1=value1 -val2=value2
Is there a way to feed non positional arguments to a shell script? Meaning explicitly specify some kind of flag?
. myscript.sh value1 value2
. myscript.sh -val1=value1 -val2=value2
Yes there is. The name is getopts http://www.mkssoftware.com/docs/man1/getopts.1.asp
Example:
Script has arguments as follows: - $0 - script name - $1, $2, $3.... - received arguments $* = all arguments, $# = number of arguments
Reference: http://famulatus.com/ks/os/solaris/item/203-arguments-in-sh-scripts.html
You can use
getopts
, but I don't like it because it's complicated to use and it doesn't support long option names (not the POSIX version anyway).I recommend against using environment variables. There's just too much risk of name collision. For example, if your script reacts differently depending on the value of the
ARCH
environment variable, and it executes another script that (unbeknownst to you) also reacts to theARCH
environment variable, then you probably have a hard-to-find bug that only shows up occasionally.This is the pattern I use:
The easiest thing to do is pass them as environment variables:
This doesn't work with csh variants, but you can use env if you are using such a shell.