Bash For Loop Spaces

www.la‮‬utturi.com
Bash For Loop Spaces

If you have a for loop in Bash that is looping over the values of a string that contains spaces, you may run into problems if you do not properly handle the spaces. This is because Bash treats each word in a string as a separate argument by default, so if a string contains spaces, the for loop will treat each word as a separate value.

To properly handle spaces in a for loop, you can use the "$@" syntax to expand the loop variable and treat the entire string as a single argument. This will allow the for loop to treat the string as a single value, even if it contains spaces.

Here is an example of how to use the "$@" syntax to handle spaces in a for loop:

my_string="hello world"

for value in "$@"; do
  echo $value
done

In this example, the my_string variable contains a string with spaces. When the for loop iterates over the values of this string, the "$@" syntax is used to expand the loop variable and treat the entire string as a single argument. This allows the for loop to properly handle the spaces in the string, and it will output the entire string on a single line, like this:

hello world

Note that the "$@" syntax only works with the for loop variable, and not with other variables. If you want to expand a regular variable that contains spaces, you can use the "$*" syntax instead. Consult the Bash documentation for more information about handling spaces in strings and using the "$@" and "$*" syntax in Bash.

Created Time:2017-10-16 14:38:38  Author:lautturi