How to Use “Set – $Variable” in Bash Scripts? [2 Examples]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

In Bash, the set command modifies shell options and parameters. When you use the set command followed by a hyphen and a variable name (set – $VARIABLE), it allows you to set the positional parameters in the shell. In this article, I am going to discuss how to set – $variable in Bash scripts. So, let’s start!

What is “set – $Variable” in Bash?

set-$VARIABLE serves to divide the value of a Bash Variable into separate words, utilizing the Internal Field Separator (IFS) as the separator. For instance, if VARIABLE holds the value “NY Ohio Miami“, executing “set – $VARIABLE” would assign the positional parameters as “NY“, “Ohio“, and “Miami“.

Initially, this might not appear exceedingly useful, but it can be a potent technique when applied appropriately. One prevalent application involves processing command-line arguments provided to a bash script. When executing a bash script, the positional parameters (i.e. $1, $2, etc.) represent the arguments passed to the script. By utilizing “set – $VARIABLE“, you can conveniently split a single argument into multiple words, enabling easier processing of the individual components.

2 Practical Examples to Use “Set – $Variable” in Bash Scripts

To understand the context fully how you can use the set – $variable command in Bash scripts, here I have provided two examples for your perusal. Check these out.

1. Using “set – $VARIABLE” in Bash Script

The set – $VARIABLE syntax allows you to set the positional parameters in a Bash script. Follow the steps specified below assign a string with the set – $VARIABLE command:

  1. At first, launch an Ubuntu terminal.
  2. Write the following command to open a file in Nano:
    nano set_variable_1.sh
  3. Copy the script mentioned below:
    #!/bin/bash
    
    # Set the value of $VARIABLE
    VARIABLE="Hello, World!"
    
    # Set the positional parameters using set - $VARIABLE
    set - "$VARIABLE"
    
    # Access and display the first positional parameter
    echo "First parameter: $1"
    
    EXPLANATION

    The value of $VARIABLE is set to “Hello, World!”. Then, using set - "$VARIABLE", the value of $VARIABLE is assigned as the first positional parameter ($1). Finally, the echo command displays the first positional parameter. It is worth mentioning that if I did not use the set – “$VARIABLE” in the code, I had to assign the VARIABLE value to the positional parameter ($1) manually to channel the command line argument to the output line. In this case, the alternate line would be VARIABLE=$1 instead of using set - "$VARIABLE.

  4. Press CTRL+O and ENTER to save the file; CTRL+X exit.
  5. Use the following command to make the file executable:
    chmod u+x set_variable_1.sh
  6. Run the script by the following command:
    ./set_variable_1.sh

    script output by using of set – $VARIABLEThe output returns First parameter: Hello, World! Where Hello, World! acts as a positional parameter of the VARIABLE variable.

2. Applying Loop on the Elements of a List Stored in a Variable

Another frequent scenario where set – $VARIABLE comes in handy is when you need to iterate over the elements of a list stored in a variable. Let’s consider an example:

#!/bin/bash

# Set the value of $VARIABLE
VARIABLE="apple orange banana"

# Set the positional parameters using set - $VARIABLE
set - $VARIABLE

# Loop through the positional parameters and display each one
for param in "$@"; do
  echo "Fruit: $param"
done
EXPLANATION

The value of $VARIABLE has been set to a string containing three fruits separated by spaces: “apple orange banana“. Next, using set - $VARIABLE, the value of $VARIABLE has been assigned as the positional parameter. This operation splits the string into separate elements and assigns them to $1, $2, and $3, respectively. Finally, The for loop iterates over the positional parameters (“$@”) and displays each fruit. The loop runs three times, once for each fruit, printing “Fruit: [fruit_name]” for each iteration.

script output by applying loopAs the VARIABLE variable stores the apple orange banana string, set – $VARIABLE fragments the string based on the whitespace and later returns Fruit: apple, Fruit: orange, and Fruit: banana using the for loop.

Assignment Task on Bash Set Variable

  1. Create a new Bash script file named “variable_operations.sh” and then do an algebraic addition of two numbers by putting them in a variable initially. You have to use the set -$VARIABLE command to do the job.
  2. Suppose you have a file composed of 100 student names in it. Now your task is to list the name along with a unique number. If you already know how to crack it, share your thoughts in the comment section and disseminate your Bash knowledge to all.
N.B: Process command-line arguments using the set – $VARIABLE command.

Conclusion

In conclusion, set – $VARIABLE is a useful bash feature that allows you to split the value of a variable into separate words, using the IFS as the delimiter. It processes command-line arguments or to loop over the elements of a list stored in a variable. If you have any questions or queries related to this article, feel free to comment below.

People Also Ask

How to set bash variable to path?

To set a Bash variable to a path, you can use the following syntax: VARIABLE_NAME="/path/to/directory". Replace VARIABLE_NAME with the desired name for your variable, and “/path/to/directory” with the actual path you want to assign.

How do you set a variable PATH?

To set the variable PATH, open the environment variables settings and find “PATH” or “Path“. Add the desired directory paths separated by ; (Windows) or : (Unix-like). Save the changes, exit the settings, and restart the command prompt/terminal. Modifying PATH allows your operating system to locate executable files without specifying their full path.

Why we use curly bracket followed by $ sign in bash?

In bash, we use ${} to reference variables in various contexts and to perform advanced operations such as string manipulation, arithmetic, and command substitution. It allows us to access the value stored in a variable and use it within a string or as an argument to a command or function.

What is set -e in Bash?

In Bash, the set -e command enables the “exit immediately if a command exits with a non-zero status” behavior.

Related Articles


<< Go Back to Variable Declaration and Assignment | Bash Variables | Bash Scripting Tutorial

Rate this post
Mohammad Shah Miran

Hey, I'm Mohammad Shah Miran, previously worked as a VBA and Excel Content Developer at SOFTEKO, and for now working as a Linux Content Developer Executive in LinuxSimply Project. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). As a part of my job, i communicate with Linux operating system, without letting the GUI to intervene and try to pass it to our audience.

Leave a Comment