Wenjia Zhai
Wenjia Zhai

Reputation: 71

how to understand the mechanism of backslash?

I'm learning bash. when I tried to enter

echo {a,b,c} ,{\ 1," 2",' 3'}

It returns

a b c , 1 , 2 , 3

While I tried to enter

echo {a,b,c}\ ,{\ 1," 2",' 3'}

It returns

a , 1 a , 2 a , 3 b , 1 b , 2 b , 3 c , 1 c , 2 c , 3

I've noticed the only difference is the second command contains \. Can someone explain the mechanism of \ or how two commands work differently? Thanks!

Upvotes: 0

Views: 41

Answers (1)

JNevill
JNevill

Reputation: 50034

A space acts as an IFS (Internal Field Seperator). The first example

echo {a,b,c} ,{\ 1," 2",' 3'}

There are two distinct groups {a,b,c} and ,{\ 1," 2",' 3'}. That first one is printed out, then the second one is expanded and printed (comma and then each item in the sequence).

In your second example, the backslash escapes the IFS which tells your shell that it's a literal space character. So

echo {a,b,c}\ ,{\ 1," 2",' 3'}

expands out each item from the first combining with 1 space and 1 comma and then each item from the second sequence producing:

 a , 1 a , 2 a , 3 b , 1 b , 2 b , 3 c , 1 c , 2 c , 3

a , 1 and a , 2 and a , 3 and b , 1 and so on as each combination (which are then separated by a space, again because it is IFS by default).

Upvotes: 2

Related Questions