Retrieve first command line argument without option

I am trying to write a shell script shell that caches information every time a command is called. He only needs to save the first argument without an option. For example, in

$ mycommand -o option1 -f another --spec more arg1 arg2

I want to get "arg1."

How can this be done in bash?

+3
source share
3 answers

Using getopt is probably the way to go.

If you want to see the argument scanning code in bash, a method without getopt:

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: "$@"
+6
source

- . bash , , . , , (.. "-f" "--file" ), , .

, DigitalRoss, case , (-), script "*)" , . , , , . "skip", .

+2

, - getopt ( ).

Perhaps save the entire command line (so that you can pass it to the real tool without changes), then process the arguments with getopt, take the necessary information and run the swap tool.

+1
source

Source: https://habr.com/ru/post/1718516/


All Articles