The “set” Command in Linux [6 Practical Examples]

The set command is a built-in command in Linux that is used to set or unset the values of shell options and positional parameters. Also, it is widely used in Bourne shell (sh), Korn shell (ksh) and C shell (csh) to get the system settings, make the variable declaration mandatory, debug a script, and so on. To do so, you can use the default set command along with its different useful options.

In this writing, I’ll walk you through the most common applications of the set command in Linux with 6 examples.

Exit Values of “set” Command

Before diving into the details, you may quickly go through the exit values of the set command:

Exit Value Description
0 Stands for successful execution of the command
1 Indicates a failure for an invalid argument
2 Denotes a failure due to a missing mandatory argument

Syntax of “set” Command

The syntax of the set command in Linux is:

set [-abefhkmnptuvxBCHP] [-o option-name] [--] [-] [arg ...]

Note: Everything inside square brackets is optional in this syntax. Three dots after arg indicate that multiple values can be passed to the argument.

Options of “set” Command

The set command can take a wide range of options. To check out all the available options, you can browse the help page for set command:

help set

The most useful options are:

Options Description
-o Enables a shell option
-a, -o allexport Marks variables that are created or modified for export
-u, -o nounset Treats unset variables as errors during substitution
-e Exits immediately if a command exits with a non-zero status
-f Disables file name generation (globbing)
-x Prints commands and their arguments as they are executed
-C, o- noclobber Disables overwriting of existing regular files by redirection of output
– – Assigns any remaining arguments to the positional parameter

Note: While you can set an option by using a dash (-) followed by the option, you can also unset it by using a plus sign (+) followed by that option.

What Does “set” Command Do?

The set command without any option displays the current environment settings. These settings often include the PATH and COMSPEC environment variables, which help find programs on disk.

default set command returns current environment settings

Also, you can use this command to control the variables and shell environment. Follow the examples below to learn the complete use of the “set” command,

6 Examples of Using the “set” Command in Linux

Here’s how you can use the set  command for setting or unsetting the values of shell options and positional parameters:

1. Making Variable Declaration Mandatory

By default, if an undeclared variable is called in a command line and everything else in the command line is correct, the command line will be executed, ignoring the undeclared variable and without displaying an error.

However, the set command with the option -u or option -o nounset treats unset variables as errors during substitution and stops the execution of that command line in the first place whenever it finds an undeclared variable in a command line. You can make variable declarations mandatory by using:

set -u

Now, set values for variables. For example:

FirstName=John 
LastName=Doe

After setting values for the variables, check them:

echo $FirstName $LastName

Finally, to demonstrate the action of the set -u command, check the values again with an unset variable (the variable we haven’t defined yet) MiddleName:

echo $FirstName $MiddleName $LastName

1. Using the set-u command to make variable declaration mandatory In the above image, you can see that, MiddleName is treated as an unbound variable as it is not declared before executing the command line. And this stops the execution of the entire line.

2. Turning off Overwriting an Existing File

To turn off overwriting an existing file, you can use the set command with the -o noclobber option. For example, write a line into a file using output redirection:

echo 'First Line'>Sample

This command will write “First Line” into a text file named Sample. You can check the content of Sample using cat sample. Now, overwrite the file content and preview it:

echo 'Second Line'>Sample 
cat Sample

The output image below shows that the above command has overwritten the previous content of the Sample file. However, to turn off this overwriting feature, execute:

set -o noclobber

Overwriting an existing file is turned off now. You can check this using:

echo 'Third Line'>Sample

set-o-noclobber command turns off overwriting an existing file
In the image above, you can see that, after using the set -o noclobber command, the file “Sample” cannot be overwritten.

3. Exporting Variables

To mark the variables that are modified or created for export, you can use the set command with the option -a or -o allexport:

set -a

Now define the variables in the terminal that you want to export. For example:

FirstName=John 
LastName=Doe

From now on, you can export these variables from the terminal to a script and use them according to your needs. For instance, let’s use them in a script named ExportVariables:

nano ExportVariables

Inside the nano window, you can use the variable in a script like this:

#!/bin/bash

echo $FirstName $LastName

using variables in a bash scriptThe variables FirstName and LastName are exported from the terminal to the script. You can check this by using:

ExportVariables

using set -a command to export variables

4. Disabling Pathname Expansion

To disable the pathname expansion, use the set command with the -f option. For example, list all the files with the “.txt” extension:

ls *.txt

This returns all the files with the .txt extension.

After that, use the set command with the -f option to disable pathname expansion:

set -f

Now using the same ls command will not list the files like before. using set -f command to disable pathname expansionYou can see that after disabling pathname expansion, ls couldn’t recognize the * expansion.

Note: In general, the wild character * along with the extension .txt will match all the .txt files in the current directory. However, using the set -f command beforehand will search for the exact file or directory named *.txt. This is useful when filenames contain special characters.

5. Debugging Shell Scripts

To debug the shell scripts, you can use the set command in Linux. Some examples are:

A. Printing the Commands with Output in the Terminal

To preview the command lines in the terminal, you can use the set command with the -x option. Then, consider these command lines:

set-x
FirstName=John 
LastName=Doe 
echo $FirstName $LastName

using set -x command to view the output in the terminal first
As in the above image, you will see a preview of each command on the terminal before they are executed using the set -x command.

B. Printing the Step by Step Output

To monitor the line-by-line execution of a bash script, you can use the set command with the -x option. Here’s how to use it in a loop in Bash script:

#!/bin/bash
set -x
n=1
while [ $n -le 3 ]
do
echo "The number is: $n"
n=$(( $n + 1 ))
done

EXPLANATION

The script iterates over a sequence of numbers from 1 to 3 and prints each number. Executing the script shows the step-by-step execution in the terminal.

using set -x command to monitor step by step output

Here, the image shows that the code is executed sequentially, one line at a time. After each line is executed, the result is displayed, and then the subsequent line is executed.

C. Exiting Execution if an Error Happens

To exit immediately as soon as an error happens in a command line or script, you can use the set command with the option -e. To see its use, create a script named StopAtError using the nano command.

nano StopAtError

Now, write the following commands in the script:

#!/bin/bash 
set -e 

#Define Variables
FirstName=John 
LastName=Doe 

echo $FirstName 
cat  MiddleName 
echo $LastName

EXPLANATION

This script is intended to print some lines that are the content of the FirstName, MiddleName and LastName. If an error occurs during execution, it will immediately exit.

using set -e command to stop executing the script as soon as any error happens

In the above image, you can see that after printing the first name, the script encounters an error as the MiddleName was not defined before. At this point, the script exits from execution without printing the LastName.

D. Exiting Execution if Error Happens with Piped Execution

To stop immediately if there’s an error in a command line or script involving piped commands, you can use the set command with the option -eo pipefail.

To demonstrate this, let’s create a script named PipeFailCheck using the nano command:

nano PipeFailCheck

In the nano window, write a script with a piped command like this:

#!/bin/bash 
set -eo pipefail 

echo "Line 1" 
echo "Line 2" | cat MiddleName 
echo "Line 3"

EXPLANATION

The code is designed to print certain texts. In the event of an error, including within a piped command, it will promptly terminate execution.

Now run the script PipeFailCheck:

PipeFailCheck

using set -eo pipefail command to exit the script execution if any error happens in a piped command line
In the above image, you can see, the echo “Line 1” command line is executed. However, there is an error message regarding the piped command echo “Line 2” | cat MiddleName stating that cat: MiddleName: No such file or directory. And so, the command lines, including the erroneous piped command and onwards, are not executed.

6. Getting Positional Parameters

You can utilize the positional parameters with the set command. The examples are:

A. Getting Positional Parameter Directly Using “set” Command

You can use the set command in Linux to assign values to positional parameters. In short, positional parameters are shell variables that can be accessed by using a dollar sign $ followed by a number. The number denotes the position of that parameter. So the syntax is:

$[N]

You can type a command line starting with set followed by some strings and use positional parameters to access the content later. For instance, write the following command in the terminal:

set John Alexander Doe

Now you can access the values by using positional parameters. The command lines are like this:

echo $1
echo $2
echo $3

using positional parameters to get the substrings from a variable
Here, echo $1 returns the first value which is John in this case, echo $2 returns the second value Alexander, and so on. Look at the following image to verify the concept.

B. Getting Positional Parameters from a Variable

You can also access the positional parameters from a variable using the set -- command.
For example, assign something to a variable and use the set -- command along with that variable:

FullName=John Alexander Doe
set -- &FullName
echo FullName

EXPLANATION
Here, the FullName variable is defined. We’ve used the set -- command along with the FullName variable and the content of the variable is displayed using the echo command.

This FullName variable contains three strings: John, Alexander and Doe. As we’ve used the set -- command along with the variable FullName, so from now on, we can use the positional parameters to access the individual strings from the variable FullName:

echo $1
echo $2
echo $3 
EXPLANATION
In this case, the dollar sign($) followed by the numbers (1,2,3) refers to the positional parameters. Here, the number stands for the position of the string in the variable. For example, echo $1 will return the first string from the variable FullName, which is “John” in this case.

And you will get an output like the following image:getting positional parameters from a variable

How to Unset a Variable in Bash?

To unset a variable, you can use the set command with the option -n or the unset command followed by the variable name. For instance, define some variables and print them:

FirstName=John 
LastName=Doe 
echo $FirstName $LastName

This substitutes the variables with their values, and the command line works properly. Now you can use the unset command to unset a variable. Let’s unset the variable LastName using:

unset LastName

Now, use the echo command to see what it returns this time:

echo $FirstName $LastName

unsetting a variable in a bash script
In the image above, you can see that, only the FirstName variable is substituted with its value, not the LastName. This is because the variable LastName was unset before executing the echo command.  

Conclusion

In this article, I’ve demonstrated the set command in Linux focusing on its most frequently used features with relevant examples. The set command serves several purposes, such as enforcing mandatory variable declarations and aiding in bash script debugging. Explore the set command and its various options on your own. Hopefully, this article will be helpful to you in understanding and using the set command.

People Also Ask

Why use the “set” command in Linux?

The set command is used in Linux to set the values of shell options as well as the positional parameters. We also use this command to make variable declarations mandatory, disable overwriting existing files, debug the shell scripts, and so on.

What are the most frequently used options in “set” command?

The set command comes up with multiple useful options. All the options have their dedicated use cases. Generally, the option -e, -o, -u, -x etc are most frequently used.

What are “set” and “unset” commands in Linux?

The set and unset commands are two useful commands in Linux that enable you to set or unset the shell options and the positional parameters.


Related Articles

5/5 - (1 vote)
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
Avatar photo

Hadi Ul Bashar holds a BSc degree in Biomedical Engineering from Bangladesh University of Engineering and Technology. In January 2023, Bashar joined Softeko as an Excel and VBA content developer. Since then, he has authored over 50 articles and created over 70 videos. Also, he has an interest in Linux. Currently, he is working as a Linux content developer executive. Here, he aims to create useful Linux content for its users. Reading books and travelling are his favourite pastimes. Read Full Bio

Leave a Comment