About
This article shows you how to pass arguments that have space characters in their values.
Explanation
The problem: the default behavior
Passing several arguments to a function that are stored as a string may not work properly when you have space in it.
Why ? because bash transforms it explicitly as an array with the read function. See the string to array example
By default, this is defined by the IFS variable as the following three whitespace characters (space, tab and end of line).
Demo:
- Setting the default value of IFS to be sure of the environment
IFS=$' \t\n'
- The string with two long option that have a spaces in their values (ie on space between hello and nico and one space between hello and world)
ARGS_AS_STRING="--longoption='hello nico' --longoption2='hello world'"
- Transform it as an argument (ie as an array)
read -r -a ARGS <<< "$ARGS_AS_STRING"
- How many arguments do we get ? 4 in place of 2
echo there is ${#ARGS[*]} arguments
4
(IFS=$'\n'; echo "${ARGS[*]}")
--longoption='hello
nico'
--longoption2='hello
world'
Solution: Define explicitly a tab as only separator
If your arguments stored as a string contains a space, you should:
- define the separator explicitly to a tab.
- set the tab in your string to define explicitly the separation
Example:
- Setting a tab in the string by replacing – with a tab and the help of sed
ARGS_AS_STRING_TAB_SEPARATED=$(echo "$ARGS_AS_STRING" | sed 's/ --/\t--/g')
- Then transform the string as an array with only the tab as delimitor
IFS=$'\t' read -r -a ARGS <<< "$ARGS_AS_STRING_TAB_SEPARATED"
- How many arguments ?
echo there is ${#ARGS[*]} arguments
2
(IFS=$'\n'; echo "${ARGS[*]}")
--longoption='hello nico'
--longoption2='hello world'