1

Say I have a script that has:

command $1

Also say command has an optional parameter so it could also be command $1 $2.

What happens if $1 includes a space here (let us assume $1=A B)? Will command be interpreted as command A B, or command A\ B where A B is a single variable?

2 Answers2

2

Typically, if $1 includes spaces and isn't double-quoted then it will be interpreted as multiple input tokens. If you want it to be interpreted as a single token then double-quote it, i.e. command "$1" $2. This is because by default white-space is used to separate tokens. This behavior can be modified by setting the value of the IFS environment variable. For more information you might consult the following page from the Advanced Bash Scripting Guide:

igal
  • 9,886
1

Depends on how the user entered it - and then how you reference it in the script

./command "a b"

or

./command a\ b

Should provide $1="a b" - if you call it elsewhere, you should wrap your argument variable in appropriate quotes - ie, "$1"

If the user simply enters

./command a b

Then $1 will contain "a" and $2 will contain "b" and $# (number of args) will be 2.

Try this script as your command command -

#!/bin/bash

echo Number of arguments given - $#

echo First argument - $1
echo second argument - $2
ivanivan
  • 4,955