Bash – Variable expansion in Bash

bashquotingshellvariable substitution

I tried the following commands

variable='one|name'
echo $variable

The output is

one|name

whereas echo one|name gives an error No command 'name' found. This is reasonable because bash treats | as a pipe and tries to execute command name with one as input.

But why does echo $variable print one|name? After Parameter and Variable expansion, shouldn't it be equivalent to echo one|name?

Version:

GNU bash, version 4.3.11(1)-release (i686-pc-linux-gnu)

Best Answer

No, it shouldn't, because of the way bash operate the command.

When you type echo one|name, bash parse the command, treats | as a pipe token, so | perform pipeline.

When you type echo $variable, because token parsing occur before variable expansion, bash parsing the command into two parts, echo and $variable. After that, it performs variable expansion, expand $variable to one|name. In this case, one|name is a string, | is a part of string and can not be treated as a pipe token (of course, the token recognition phrase was done). The only thing it can be special if IFS variable contains |, bash will use | as delimiter to perform field spliting:

$ variable='one|name'
$ IFS='|'
$ echo $variable
one name