9 Examples of Using the set Command to Set Environment Variables

Try this guide with our instant dedicated server for as low as 40 Euros

linux set command

The shell you use on your Linux system interprets the user commands and invokes appropriate utilities and commands. 

Variables are a critical aspect of working with shells in Linux distributions. The active shell checks these variables to get the relevant information about the paths to installed software, modify the default behavior of the scripts, and set aliases for long commands.

Linux provides a set as a native utility for working with shell environment variables. 

In this tutorial, we will explore the set command in Linux. In addition to the basic syntax, we will discuss nine examples that demonstrate the capabilities of this utility.

Let’s start with a brief introduction to the set command in Linux. 

Table Of Contents

  1. What is the set Command in Linux?
    1. The Linux set Command Syntax
    2. Options For the Linux set Command
  2. 9 Practical Examples of the Linux set Command
    1. The Prerequisites
    2. Example #1: Use the set Command to List All Settings
    3. Example #2: Use set in Debugging Scripts
    4. Example #3: Share Variables and Functions
    5. Example #4: Stop on Error
    6. Example #5: Avoid Overwriting Files
    7. Example #6: Highlight Missing Variables
    8. Example #7: Assign Values to Positional Parameters
    9. Example #8: Splitting Strings
    10. Example #9: Enabling Automatic Export and Job Notifications
  3. Conclusion
  4. FAQS

What is the set Command in Linux?

The set command is an integral component of all mainstream Linux distributions. It is used to display and modify the name and values of shell and environment variables. This command is widely used across Unix-like operating systems and functions smoothly in diverse shell environments, including the Bourne shell (sh), C shell (csh), and Korn shell (ksh).

The Linux set Command Syntax

The basic structure of the set command in Linux is as follows:

# set [options] [arguments]

Options

[options] refer to specific flags or settings that you can add to the set command to alter the operating environment of the Bash shell. These options are crucial for tailoring the behavior of shell scripts to meet specific operational requirements.

To activate an option, prepend it with a minus sign () followed by the desired option letter.

Conversely, to deactivate an option, use a plus sign (+) followed by the option letter.

Arguments

The term [arguments] corresponds to positional parameters that are sequentially allocated to the following variables:

$1

$2

...

$n

In instances where no options or arguments are provided, the set command will default to displaying all variables within the shell environment.

Exit Values

The execution of the set command can result in one of three possible exit statuses:

0: This status indicates that the command was executed successfully without any issues.

1: This exit value signifies a failure due to an invalid argument.

2: This status is returned when there is a failure triggered by the absence of a required argument.

Options For the Linux set Command

The set command in Linux comes with a comprehensive array of options, allowing for a versatile combination of functionalities.

Many of these options can also be accessed using an -o flag, providing an alternate method of invocation.

Consider the following table that lists both the options and -o flags. 

options available in linux set command

Additionally, the following table presents some options that only have the -o options:

linux set command more options

Also Read: 6 Simple Examples of Using the Linux watch Command

9 Practical Examples of the Linux set Command

Now that you have a clear understanding of the syntax and options, we will now present the following examples that illustrate the capabilities of the set command in Linux.

But first, let’s check out the prerequisites for using the command.

The Prerequisites

Make sure you have the following:

  • A system running any mainstream Linux distribution
  • Basic understanding of shell commands

Example #1: Use the set Command to List All Settings

When you type set at the command line without adding anything else, it shows you a long list of settings, including variables and the values they’re set to for the commands and actions.

Note that the list can be long, and we recommend using the Page Up and Page Down buttons on your keyboard.

Here’s a little look at what comes up when we enter the command on our test machine:

Use the set Command to List All Settings

Also Read: 13 Examples That Showcase the xargs Command in Linux

Example #2: Use set in Debugging Scripts

The set command is particularly useful in debugging scripts. 

By using the -x option, you can track each command in your script as it runs, along with its output. This step-by-step look into script execution is a great way of pinpointing issues.

Let’s run through a typical scenario where we will use the -x option with the set command to see the execution of a script.

Step #1: Run the set Command

Start by running the following command in the terminal:

# set -x

Step #2: Write the Script

Open your preferred text editor (for this demonstration, we’ll use the vi editor) to write the script. Our test script has a basic loop script that will illustrate the effects of the -x option:

Here are the statements you need to add to your script:

x=10

while [ $x -gt 0 ]; do

         x=$[ $x-1 ]

         echo $x

         sleep 2

done

Step #3: Make the Script Executable

Once you have the script, the next step is to change the script’s permissions to make it executable. Generally, you’ll need to do this every time before you run a script. 

In this demonstration, we will use the chmod utility to change the execution permissions for the script:

# chmod +x [script-name.sh]

Also Read: lsof Command in Linux with Examples

Step #4: Execute and Observer

Finally, run the following command to execute the script: 

# ./[script-name.sh]

As you can see, the output displays each line of the script one by one, executes it, presents any resulting output, and then proceeds to the next line.

Execute and Observer

Alternatively, you can activate debugging mode by adding the -x option directly into the script’s shebang line:

#!/bin/bash -x

Example #3: Share Variables and Functions

You can make any variable or function immediately available to other scripts and subshells by using the -a option. This option allows the set command to automatically export them to all scripts and subshells.

Run the following command to turn on this feature:

# set -a

Here’s an example of how this export function works. 

We have set two variables, name and age, that we will use for the demonstration. We have set the -a flag for the set command so that we can export these variables, making them accessible in subshells or scripts. 

# set -a

 # name='June'

 # age=24

Next, we create a script that will output the current values of these variables:

#!/bin/bash

echo $name $age

Finally, execute the script with the bash command in the terminal:

# bash export.sh

June 24

Share Variables and Functions

Example #4: Stop on Error

The -e option tells a script to stop running if it hits an error. 

This is a useful functionality that allows the script to avoid further issues by stopping the execution at the first error.

We will demonstrate this functionality with a script. 

Launch your preferred text editor and add the following lines to it:

#!/bin/bash

set -e

cat nonexistingfile

echo "The end"

As can see, the script started execution and hit the error when it tried to use the cat command to access the nonexistingfile file. As the name suggests, this file is not available, and the cat command will raise an error. Since we have enabled the -e flag of the set command, the script will stop execution and display the error message generated by the cat command. 

Example #5: Avoid Overwriting Files

By default, Bash will overwrite files if you redirect output to them. But if you use the -C option, this default behavior changes, and Bash will not overwrite any file that already exists when you use >, >&, or <> for redirecting output.

Avoid Overwriting Files

Consider the following scenario where we redirected output, and Bash lets us overwrite the listing.txt file. But once we execute the set -C command, Bash will display an error message indicating that it can’t overwrite an existing file.

Example #6: Highlight Missing Variables

Normally, Bash overlooks variables that don’t exist and proceeds with those that do. This behavior can often lead to errors that are very difficult to track down to the source. 

However, by applying the -u option, Bash is instructed not to ignore missing variables and raise an alert when it encounters one.

For instance, consider the following script that we execute in the situation where we have not set the -u option for the set command. In this case, Bash ignores the fact that $var2 isn’t defined. 

#!/bin/bash

var1="123"

echo $var1 $var2

The output of the script contains only the value of $var1:

Highlight Missing Variables

Next, we changed the script by adding the set -u statement that prevents Bash from ignoring the problem and reporting it:

#!/bin/bash

set -u

var1="123"

echo $var1 $var2

You can see that Bash raised the error with the set -u command in the script. 

Example #7: Assign Values to Positional Parameters

The set command can assign values to positional parameters in a shell script. Positional parameters are special shell variables accessed through the following syntax:

$[N]

where N represents a numerical value corresponding to the parameter’s position.

The digit inside the square brackets, denoted by [N], indicates the position of the parameter. For instance, $1 represents the first positional parameter, $2 represents the second parameter, and so on.

For instance, consider the command:

# set first second third

When you run this command, it assigns the value first to the $1 positional parameter, second to $2, and third to $3

You should verify this assignment using the echo command:

# echo $2

Assign Values to Positional Parameters

You can also unset positional parameters by running the following set command syntax:

set --

Example #8: Splitting Strings

You can utilize the set command to split strings into separate variables based on spaces as the separator. For instance, consider a variable named myvar containing the string This is a testing.

# myvar="This is a testing"

# set -- $myvar

# echo $1

# echo $2

# echo $3

# echo $4

Splitting Strings

This code assigns each word in myvar to separate variables using set and then prints out each variable separately using echo.

Example #9: Enabling Automatic Export and Job Notifications

Using the -o allexport flag ensures that all subsequently defined variables are automatically exported, while the -o notify flag prompts the shell to immediately display task completion messages.

To activate these flags, execute the following command:

# set -o allexport -o notify

In this example, observe how the shell promptly notifies you upon the completion of a background job, thanks to the script being exported:

Enabling Automatic Export and Job Notifications

Tip: To run a process in the background, simply append an ampersand (&) at the end of the command. Alternatively, you can use the crontab and the system’s cronjob management capabilities to schedule scripts and commands. 

Conclusion

Now that you’re familiar with the versatile set command in Linux, you have a powerful tool at your disposal to optimize your Linux environment. Experiment with its various options to gain deeper insights and enhance your control over the Linux ecosystem utilized by diverse packages.

Looking to leverage Linux hosting solutions with top-notch performance and reliability? Explore RedSwitches for premium Linux hosting services tailored to your needs!

We have the best dedicated server pricing and deliver instant dedicated servers, usually on the same day the order gets approved. Whether you need a dedicated server, a traffic-friendly 10Gbps dedicated server, or a powerful bare metal server, we are your trusted hosting partner.

FAQs

Q. Linux set command: What is it and how to use it?

The Linux set command serves the purpose of configuring or unconfiguring shell options and positional parameters. It allows you to change the behavior of the current shell environment or use it to initialize shell variables.

Q. What are some practical examples of using the set command in Linux?

Here are 9 practical examples of using the set command in Linux:

set option: To enable a specific option for the shell, you can utilize the set command followed by the option’s name.

Unset option: Similarly, to turn off a specific option for the shell, you can use the set -o followed by the option name.

Set positional parameters: You can set positional parameters for a shell script using the set command followed by the parameters.

Unset positional parameters: To unset positional parameters, you can use the set — followed by the parameters.

Set environment variables: Using set, you can easily initialize environment variables for the shell

Q. How can I display all shell variables and functions using the set command?

The primary function of the set command is to configure or reveal shell options and positional parameters within a shell environment.

Q. What does the -e option do in the set command?

The -e option causes the shell to exit immediately if any command exits with a non-zero status, effectively halting the script’s execution upon encountering an error.

Q. How can I enable debugging mode using the set command?

You can enable debugging mode by using the -x option with the set command. This option causes the shell to print each command before executing it, allowing you to trace the execution flow of your script.

Q. What does the -u option do in the set command?

The -u option causes the shell to treat unset variables as errors, resulting in an immediate exit if any referenced variable is not set.

Q. How can I export variables automatically in Linux using the set command?

You can use the -a option with the set command to automatically export all subsequently defined variables, making them available to subshells and scripts.

Q. What is the purpose of the -o option in the set command?

The -o option is used to set or unset various shell options. For example, -o errexit sets the shell option to exit immediately if a command exits with a non-zero status.

Q. How can I display the current value of a specific shell option using the set command?

You can use the -o option followed by the name of the shell option to display its current value. For example, set -o errexit will display whether the errexit option is currently set or unset.

Q. What does the -C option do in the set command?

The -C option configures the shell to prevent overwriting existing files when using output redirection (>, >&, or <>).

Q. How can I set positional parameters using the set command?

You can set positional parameters by using the set command followed by the desired values. For example, set — arg1 arg2 arg3 sets the positional parameters $1, $2, and $3 to arg1, arg2, and arg3, respectively.

Try this guide with our instant dedicated server for as low as 40 Euros