Bash set

From NovaOrdis Knowledge Base
Revision as of 21:37, 24 January 2020 by Ovidiu (talk | contribs) (→‎+x)
Jump to navigation Jump to search

External

Internal

set and Positional Parameters

arg="a b c"
set - ${arg}

assigns "a", "b", "c" to positional parameters $1, $2 and $3. Note that this assignment totally overwrites the existing positional parameters, if any. '-' that follows the builtin signals the end of options and causes all remaining arguments to be assigned to the positional parameters. This prevents arguments that start with "--..." to be interpreted as set arguments and to interfere with set function. If "-" is not specified, and the first of the space-separated arguments contains '--', set will try to interpret that sequence of characters and will produce:

set: --: invalid option

If ${arg} is empty, set - ${arg} is a noop and it does not override existing positional parameters. Use set -- or equivalent to unset existent positional parameters, if ${arg} is empty.

An indexed array can be used to initialize positional parameters too:

declare -a ARGS
ARGS=("a" "b" "c")
set - "${ARGS[@]}"

If ${ARGS} is empty, set - "${ARGS[@]}" is a noop and it does not override existing positional parameters. Use set -- or equivalent to unset existent positional parameters, if ${ARGS} is empty.

Difference between - and --

--

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

-

Signal the end of options, cause all remaining args to be assigned to the positional parameters. The -x and -v options are turned off. If there are no args, the positional parameters remain unchanged.

Unset Positional Parameters

set --

Alternative:

shift $#

List Separator

The default list separator is space. That can be changed by setting the value of the IFS variable before executing set.

Example:

arg="a,b,c"
IFS=","
set ${arg}

will identically assign "a", "b", "c" to positional parameters $1, $2 and $3.

Note you must set IFS back to whitespace after setting it to something else, so the basic shell function work as expected. This is done as shown here: restoring the default IFS value.

For more details about IFS see:

IFS

-x

After expanding each simple command and for, case and select commands, display the expanded value of PS4, followed by the command and its expanded arguments or associated word list. Useful in debugging.

+x

Prevents commands from being echoed at stdout. It is useful to start a script with set +x in case sensitive credentials are specified in commands.

set -o pipefail

https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/