set
is a shell builtin, used to set and unset shell options and positional parameters.
Without arguments, set
will print all shell variables (both environment variables and variables in current session) sorted in current locale.
You can also read bash documentation.
There're a few caveats.
set "$var"
will assign var
value to $1
. If $var
starts with -
or +
, then $var
content will be treated as sequences of shell options. If $var
contains any invalid options, most POSIX shells will print the error. yash
and zsh
in sh
, ksh
emulation are not only printing the error, but also setting valid options. While yash
stops setting options on the first invalid option, zsh
will assign all of them. In yash
:
var=-fxd; set "$var"
f
and x
will be present in $-
, while:
var=fdx; set "$var"
only f
is present in $-
. In both cases, f
and x
will be present in $-
with zsh
in sh
and ksh
emulation.
To protect you from that situation, you can pass --
as the first argument to set a positional parameter even if it starts with -
or +
:
var=-fdx; set -- "$var"
will assign $var
to $1
, regardless of its content.
set --
without any further arguments will unset all positional parameters.
If the first argument is -
, the behavior is unspecified. All known POSIX shells will unset x
and v
options (except posh
), and assign anything after -
to positional parameters:
set -xv - -f
will assign -f
to $1
. set -
also did not unset positional parameters. Schily osh also behaves like that. Heirloom sh does not unset v
and x
options.
The only POSIX shell exception is yash
, which treats -
as the first positional parameter:
$ yash -c 'set -xv - -f; printf "%s\n" "$@"; printf "%s\n" "$-"'
+ printf %s\n - -f
-
-f
+ printf %s\n cvx
cvx
Schily sh even doing nothing if -
is present in arguments:
$ schily-sh -c 'set -v - -f; printf "%s\n" "$@"; printf "%s\n" "$-"'
<blank line>
s
$ schily-sh -c 'set -v -- -f; printf "%s\n" "$@"; printf "%s\n" "$-"'
-f
vs