Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving the First Non-Option Command Line Argument

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?

like image 605
user122147 Avatar asked Sep 25 '09 02:09

user122147


People also ask

How do you reference the first command line argument?

argv[1] points to the first command line argument and argv[n] points last argument.

What is non option 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.

How do you pass an argument to a command?

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.

What is the difference between a command option and a command argument?

options help define how a command should behave. Some may be optional. arguments tell commands what object to operate on.


1 Answers

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: "$@"
like image 57
DigitalRoss Avatar answered Sep 24 '22 05:09

DigitalRoss