Bash - How to pass arguments that have space in their values ?

1 - About

This article shows you how to pass arguments that have space characters in their values.

3 - Explanation

3.1 - 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'

3.2 - 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

  • Print in a subshell (subprocess) to not set IFS. Bingo !

(IFS=$'\n'; echo "${ARGS[*]}")


--longoption='hello nico'
--longoption2='hello world'



Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap