Shell tricks - Programming On Unix

Users browsing this thread: 1 Guest(s)
josuah
Long time nixers
playing with "$@"

As you may know, in sh, $0, $1, $2, $3... $9, $* and $@ are special variables holding the command line arguments.

$0 is the name of the program and $1 ... $9 the program parameters.

$# is a number: the count of all arguments (starting from $1, unlike argc in C).

$* is a concatenation of $1 ... $9 with spaces.

$@ is an array, not just one string, but a list of strings:

Code:
$ func() { printf '"%s"\n' "$@"; }
$ func '1 2' 3 4
"1 2"
"3"
"4"

Even though `$@' was quoted, printf received multiple arguments.

You can edit $1 -> $9 with the `set' built-in command:
  • `set "$@"' does not change anything.
  • `set new "$@"' insert `new' before all the arguments,
  • `set "$1" "$2"' keeps only $1 and $2,

And the `shift' built-in command:
  • `shift' removes the first argument from the argument stack (or error).
  • `shift 2' removes the first 2 arguments from the argument stack.

The first argument is $1, but what about the last?

Code:
for last in "$@"; do continue; done

This last will take all $@ values until the end and keep the last value after the loop.

If you are using these a lot, you probably should use a programming language. ;)


Messages In This Thread
Shell tricks - by josuah - 13-11-2017, 05:27 AM
RE: Shell tricks - by josuah - 13-11-2017, 05:39 AM
RE: Shell tricks - by venam - 14-11-2017, 01:53 AM
RE: Shell tricks - by josuah - 23-11-2017, 07:59 AM
RE: Shell tricks - by josuah - 23-11-2017, 08:52 AM
RE: Shell tricks - by josuah - 04-12-2017, 07:43 AM
RE: Shell tricks - by z3bra - 04-12-2017, 08:11 PM
RE: Shell tricks - by josuah - 05-12-2017, 08:07 AM
RE: Shell tricks - by josuah - 05-12-2017, 09:02 AM
RE: Shell tricks - by josuah - 05-12-2017, 09:08 AM
RE: Shell tricks - by josuah - 08-12-2017, 12:25 PM