Sometimes it is necessary to emulate and verify the above variables in small examples and then can be copied immediately to some script, etc.
I tried to solve by using a simple example in the following ways:
(find $1) /tmp
sh -c '(find $1) /tmp'
sh -c "find $1" /tmp
echo '(find $1) /tmp' | sh
and with other combinations. Also experimented by adding the shebang interpreter directive #!/bin/sh -x
, but did not get the desired result.
Can I do this simply?
Best Answer
The first argument after
sh -c inline-script
goes to$0
(which is also used for error messages), and the rest go in$1
,$2
...So you want:
(in the olden days, you could find
sh
implementations where the first arg went into$1
instead, so you would do:Or:
to account for both behaviours, but those shells are gone now that POSIX is prevalent and publicly available).
If you want to set
$1
,$2
in a local scope within the current shell, that's where you'd use functions. In Bourne-like shells:Some shells support anonymous functions. That's the case of
zsh
:Or
es
:To change the current positional parameters, permanently, the syntax is shell dependant. dchirikov has already covered the Bourne-like shells (Bourne, Korn,
bash
,zsh
, POSIX,ash
,yash
...).The syntax is:
However, you need:
To empty that list (or
shift "$#"
) andto set
$1
to something starting with-
or+
, so it's a good habit to always useset --
especially when using arbitrary data such asset -- "$@" other-arg
to add arguments to the end of the positional parameter list.In shells of the
csh
family (csh
,tcsh
), you assign to theargv
array:In shells of the
rc
family (rc
,es
,akanga
), to the*
array:Though you can also assign elements individually:
In
fish
, the positional parameters are in theargv
array only (no$1
,$@
there):In
zsh
, for compatibility withcsh
, you can also assign to theargv
array:And you can also do:
That means you can also do things like:
to add an argument to the end, and:
to remove an argument from the end or the middle, which you can't easily do with other shells.