set - Linux


The set command in Linux is used to set or unset values of shell options and positional parameters, or to display the names and values of shell variables. This command can manipulate both the behavior of the shell and the variables stored within it, making it effective for configuring shell scripts or interactive shell environments.


The basic syntax of the set command is as follows:

set [options] [arguments]
  • options: Flags that modify the behavior of the shell.
  • arguments: Variables or values to be set.

Without any options or arguments, set will display the names and values of all shell variables.


The set command includes several options that alter its behavior:

  • -e: Exit immediately if a command exits with a non-zero status.
  • -f: Disable filename expansion (globbing).
  • -n: Read commands but do not execute them (useful for syntax checking).
  • -u: Treat unset variables as an error when substituting.
  • -v: Print shell input lines as they are read.
  • -x: Print commands and their arguments as they are executed.
  • -o option-name: Set the variable corresponding to option-name to true.
  • +o option-name: Set the variable corresponding to option-name to false.

For boolean shell options, using - sets the option and + unsets it.


Example 1: Display all shell variables and their values:


Example 2: Enable debugging to display commands as they are executed:

set -x

Example 3: Strict mode script, exiting on error or unset variable:

set -eu

Example 4: Set positional parameters $1, $2, and $3:

set -- first second third
echo $1 $2 $3

Common Issues

  • Unset Variables: Using -u can lead to scripts exiting unexpectedly if variables are not previously defined or are typoed.

    Solution: Always declare variables before use, especially in strict modes.

  • Debug Information Overload: Using -x can generate a lot of output for complex scripts, making it hard to follow.

    Solution: Use set +x to disable debugging once necessary parts are verified.


set is often combined with other commands in scripts to control error handling and script behavior:

set -euo pipefail
cat nonexistentfile.txt
echo "This won't run if the file doesn't exist."

Here, set -euo pipefail is a common pattern enabling rigorous error handling in scripts.

  • unset: Command used to delete shell and environment variables.
  • export: Mark variables for automatic export to the environment of subsequently executed commands.
  • env: Set environment for command execution.
  • bash and sh: Popular shell interpreters where set is frequently used.

For further reading and more details, visit the official GNU Bash documentation at GNU Bash manual.