-1

I would like to understand what the following command does

set -- "$@" "-h"

The gnu manual says

--

  If no arguments follow this option, then the positional parameters are unset.    
  Otherwise, the positional parameters are set to the arguments, even if some
  of them begin with a ‘-’.

I cannot take much useful information from such description though.

As I understand it, the following appends -h to the function argument list.

set -- "$@" "-h"

But, how is it that the following actually replaces --help with -h, etc.

 printf '%s\n' "$*"
 for arg in "$@"; do
   shift
   printf '%s\n' "--> arg: $arg"
   case "$arg" in
     "--Version")   set -- "$@" "-V"   ;;
     "--usage")     set -- "$@" "-u"   ;;
     "--help")      set -- "$@" "-h"   ;;
     "--verbosity") set -- "$@" "-v"   ;;
     *)             set -- "$@" "$arg" ;;
   esac
 done
Nigel
  • 39
  • 4
  • take a look at here https://www.javatpoint.com/linux-set-command#:~:text=Linux%20set%20command%20is%20used,tasks%20without%20facing%20any%20issue. – Benyamin Aug 29 '21 at 18:59

1 Answers1

4

Short answer: it adds -h to the end of the current argument list (aka the positional parameters).

Long answer: "$@" expands to the current argument list (i.e. the list of arguments passed to the current script, function, or whatever the relevant context is). set -- whatever replaces the current argument list with whatever's after the --. Thus, it replaces the current argument list with... the current argument list followed by -h.

For example, suppose we're in a script that was run with ./scriptname foo bar baz. Then the argument list is foo, bar, baz (i.e. $1 is "foo", $2 is "bar", and $3 is "baz"). In the script,

set -- "$@" "-h"

expands to the equivalent of:

set -- "foo" "bar" "baz" "-h"

...which sets the argument list to foo, bar, baz, and -h.

Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151