Beginners Guide for Set Command in Linux

Linux TLDR
Last Updated:
Reading time: 5 minutes

The set command is a built-in Linux command that can display or modify the value of shell attributes and positional parameters inside the current shell environment.

This modification can help to debug your script by finding undefined variables, errors, job control, printing commands as they are executed, and automatically exporting variables and functions in sub-shell.

Tutorial Details

DescriptionSet
Difficulty LevelLow
Root or Sudo PrivilegesNo
Host System and ArchitectureUbuntu 22.10 (x64)
OS Compatibility Ubuntu, Manjaro, Fedora, etc.
Prerequisitesset
Internet RequiredNo
Discussed Tools in this Article

Syntax of the Set Command

The set command takes two arguments: one is the option, and the other is the argument.

$ set [OPTION] [ARGUMENT]

Understanding the [OPTION]

The “option” is used to set or unset attributes or parameters in the current shell environment, affecting the behavior of your scripts and helping execute the desired tasks.

The following is a list of the most relevant options used with the set command.

Note: To turn off or unset the following options, simply replace the minus sign (“-“) with a plus sign (“+“) followed by the appropriate option.

OptionsDescription
-aMark variables that are modified or created for export.
-bAlert the user on background job termination.
-eOnce the shell receives a non-zero exit status, it will terminate the script execution immediately.
-fDisable file name generation (globbing).
-hEnable saving the commands by default as they are looked up.
-kAll assignment arguments are placed in the environment for a command, not just those that precede the command name.
-mDisplay a message when a task completes.
-nMonitor commands but not execute them.
-pDisable the processing of the “$ENV” file and the import of shell when the real and effective user ids do not match.
-tExit immediately after reading the first command.
-uTreat unset or undefined variables as an error when substituting, except for special parameters like wildcard.
-vPrint out shell input lines while reading them.
-xPrint commands with their arguments as they are executing.
-CIf set, disallow existing regular files to be overwritten by the redirection of output.

Understanding the [ARGUMENT]

The “argument” is a positional parameter or variable that holds a value that can be used in a shell script.

The positional parameter will reference the position of the value as “${N}” in order, where “N” denotes the position of the parameter.

$1
$2
...
$n

For example, “$1” is the first positional parameter after the command. The “$2” value is the second parameter, and so on.

Also Read: What is Exit Status Code ($?) in Linux

Exit Status

The exit status comes in handy when using the set command within your script to manage the flow of your shell script.

The set command has three exit statuses:

  • 0: Successful.
  • 1: Failure caused by an incorrect argument
  • 2: Failure is caused when an expected argument is missing.

Using the Set Command Without Options

Running the set command without an argument or options will print the long list of shell variables with their names and values.

$ set

The list will be too long, so you can pipe the command with the “less” keyword to enable interactive reading.

$ set | less

Turn Script Debugging Information On or Off

The “-x” flag is used to turn on script debugging information that will print each command as they are executed in the output to help you understand the behavior of your script.

To understand the usage of this option, create a file with the name “script.sh” and copy the following content into it.

echo "Hi"
echo "its"
echo "Trend"
echo "Oceans"

To run your shell script, give it the necessary executable permission using the chmod command.

$ chmod u+x script.sh

Now, before executing the script, enable debugging using the “-x” flag.

$ set -x

Execute your shell script.

$ ./script.sh 
+ ./script.sh
Hi
its
Trend
Oceans

This option will print the commands in the sequence as they are executed, moving each step one by one.

Another way to use this option within your script is by specifying the “-x” flag on the shebang line.

#! /bin/bash -x

Execute the following command with the plus sign “+” to turn off script debugging information.

$ set +x

Setting Positional Parameters With the Set Command

Directly specify the values as an argument to the set command with a space to reference each value as “${N}” in order, where “N” denotes the position of the parameter.

$ set apple banana cat dog
$ echo $1
apple
$ echo $2
banana
$ echo $3
cat
$ echo $4
dog

Execute the echo command with “$*” to print the values of all parameters.

$ echo $*
apple banana cat dog

You can even split the variable values based on spaces using the “set -- [VARIABLE]” command.

$ fruit="apple banana cat dog"
$ set -- $fruit
$ echo $1
apple
$ echo $2
banana
$ echo $3
cat
$ echo $4
dog

Use the “--” with the set command to remove the assigned values from the positional parameters.

$ set --
$ echo $*

Exporting Variables or Functions to a Sub-Shell

By default, whenever you can create variables or functions, they are only accessible from the parent shell in which they were created.

However, you can use the “-a” flag to export the variables or functions inside the sub-shell.

Without flag:

$ site=linuxtldr.com
$ bash
$ echo $site

With flag:

$ set -a
$ site=linuxtldr.com
$ bash
$ echo $site
linuxtldr.com

Immediately Exit When Command Fails

During the script execution, if it encounters any errors, it will print the error on the screen and keep executing the rest of the commands in the script.

The following is the script that includes an error.

echo "Hi"
its
echo "Trend"
echo "Oceans"

The following is an example of executing the script without any error control:

$ ./script.sh 
Hi
./script.sh: line 2: its: command not found
Trend
Oceans

As you can see, the script kept executing even after the error.

To prevent this behavior of script execution, use the “-e” flag to prevent the script immediately after it encounters its first error.

The following is the previous script with error control.

set -e
echo "Hi"
its
echo "Trend"
echo "Oceans"

The following is an example of executing the above script with error control:

$ ./script.sh 
Hi
./script.sh: line 3: its: command not found

Note that this method will not prevent error control during pipe execution.

For example, the following is the same script, but an error is piped with the echo command.

set -e
echo "Hi"
wrong-command | echo "its"
echo "Trend"
echo "Oceans"

If you run the above script even with the “-e” flag, it will keep executing after it encounters an error.

$ ./script.sh 
Hi
its
./script.sh: line 3: wrong-command: command not found
Trend
Oceans

Use “set -eo pipefail” instead of “set -e” to overcome this problem.

set -eo pipefail
echo "Hi"
wrong-command | echo "its"
echo "Trend"
echo "Oceans"

Executing the script.

$ ./script.sh 
Hi
./script.sh: line 3: wrong-command: command not found
its

Prevent File Overwriting using the Redirection Symbol

The default setting in Bash is to keep overwriting the specified file using the “>“, “>&“, or “<>redirection symbols. However, you can overcome this problem using the “-C” flag.

$ echo "Overwriting" > file.txt   #File overwritten
$ echo "Overwriting" > file.txt   #File again overwritten
$ set -C                                          #Disallowing file from being overwriting
$ echo "Overwriting" > file.txt   #Unable to overwrite the file
bash: file.txt: cannot overwrite existing file

The above file can still be overwritten using the “>>” redirection symbol.

$ echo "Overwriting" > file.txt
bash: file.txt: cannot overwrite existing file
$ echo "Overwriting" >> file.txt

Restrict Undefined Variables

Whenever you execute the script file while calling undefined or unbound variables, the script keeps executing without throwing any errors.

The following is the script calling an undefined variable.

echo "Welcome"
$st
echo "Bye"

Even if the value of the variable “$st” is not assigned, the script will keep executing.

$ ./script.sh 
Welcome
Bye

Use the “set -u” command at the top of the script to restrict the execution of the script after it encounters the first unbound variable during execution.

set -u
echo "Welcome"
$st
echo "Bye"

Executing the script:

$ ./script.sh 
Welcome
./script.sh: line 3: st: unbound variable

Set Allexport and Notify Flags

Use the “-o allexport” flag to automatically export all subsequently defined variables, with the “-o notify” flag to print the job completion messages.

$ set -o allexport -o notify
$ rm script.sh &
[1] 35291
$ [1]+  Done                    rm script.sh

And that was the end of this article.

If you have any suggestions or questions related to this topic, feel free to ask them in the comment section.

Join The Conversation

Users are always welcome to leave comments about the articles, whether they are questions, comments, constructive criticism, old information, or notices of typos. Please keep in mind that all comments are moderated according to our comment policy.