Open In App

Set – $VARIABLE” in bash

Last Updated : 23 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In the world of bash scripting, you may come across the phrase “set – $VARIABLE”. But what does it mean?

At its most basic, “set – $VARIABLE” is used to split the value of a bash variable into separate words, using the Internal Field Separator (IFS) as the delimiter. For example, if VARIABLE has the value “a b c”, then running “set – $VARIABLE” would set the positional parameters to “a”, “b”, and “c”.

This may not seem particularly useful at first glance, but it can be a powerful tool when used in the right context. One common use case is to process command-line arguments passed to a bash script. When you run a bash script, the positional parameters (i.e., $1, $2, etc.) represent the arguments passed to the script. By using “set – $VARIABLE”, you can easily split a single argument into multiple words, allowing you to process them more easily.

Here’s an example of how this might be used:

#!/bin/bash

# Set the value of VARIABLE to the first command-line argument
VARIABLE="$1"

# Split the value of VARIABLE into separate words
set - $VARIABLE

# Loop over the words
for word in "$@"; do
 echo "$word"
done

 

If you save this script as “example.sh” and run it like this:

./example.sh "a b c"

Output:

 

a
b
c

 Loop over the elements of a list stored in a variable

Another common use case for “set – $VARIABLE” is to loop over the elements of a list stored in a variable. For example:

# Set the value of VARIABLE to "a b c"
VARIABLE="a b c"

# Split the value of VARIABLE into separate words
set - $VARIABLE

# Loop over the words
for word in "$@"; do
 echo "$word"
done

 

Output:

 

a
b
c

It’s worth noting that “set – $VARIABLE” only works if the value of VARIABLE is a single string. If VARIABLE is an array, you’ll need to use a different approach. One option is to use the “printf ‘%s\n’ “${VARIABLE[@]}” syntax, which expands the array into a series of separate words, each separated by a new line character.

Here’s an example of how this might be used:

#!/bin/bash

# Set the value of VARIABLE to an array containing "a", "b", and "c"
VARIABLE=("a" "b" "c")

# Expand the array into a series of separate words
set - $(printf '%s\n' "${VARIABLE[@]}")

# Loop over the words
for word in "$@"; do
 echo "$word"
done

 

Output:

 

a
b
c

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 can be used to process command-line arguments or to loop over the elements of a list stored in a variable. While it only works with single strings, there are alternative approaches that can be used with arrays. Understanding how “set – $VARIABLE” works and when to use it can be a valuable addition to your bash scripting toolkit.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads