I am trying to write a wrapper shell script that caches information every time a command is called. It only needs to store the first non-option argument. For example, in
$ mycommand -o option1 -f another --spec more arg1 arg2
I want to retrieve "arg1."
How can this be done in bash?
argv[1] points to the first command line argument and argv[n] points last argument.
A non-option argument is an argument that doesn't begin with - , or that consists solely of - (which who treats as a literal file name but many commands treat as meaning either standard input or standard output). In addition, some options themselves have an argument.
Arguments can be passed to the script when it is executed, by writing them as a space-delimited list following the script file name. Inside the script, the $1 variable references the first argument in the command line, $2 the second argument and so forth. The variable $0 references to the current script.
options help define how a command should behave. Some may be optional. arguments tell commands what object to operate on.
Using getopt is probably the way to go.
If you wanted to see argument scanning code in bash, the non-getopt way is:
realargs="$@"
while [ $# -gt 0 ]; do
case "$1" in
-x | -y | -z)
echo recognized one argument option $1 with arg $2
shift
;;
-a | -b | -c)
echo recognized zero argument option $1, no extra shift
;;
*)
saveme=$1
break 2
;;
esac
shift
done
set -- $realargs
echo saved word: $saveme
echo run real command: "$@"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With