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

Bash Liste Des Attaques Ovh

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

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

  • Print in a subshell (subprocess) to not set IFS. Bingo !
(IFS=$'\n'; echo "${ARGS[*]}")
--longoption='hello nico'
--longoption2='hello world'






Discover More
Bash Liste Des Attaques Ovh
Bash - (Argument|Positional Parameter)

An argument is a parameter given: to a command to a function or to the bash shell They are referenced by position. A positional parameter is a parameter denoted: by one or more digits, ...
Process States
Command Argument

This page is argument of a command. When the command is started via a shell script (manual or automatic), the arguments: are separated by one or more blank space should be quoted if the value...



Share this page:
Follow us:
Task Runner