Reputation: 159
When I write export X="test"
in a file test.sh
and do $(cat test.sh)
in shell quote stay, i.e. echo $X
gives "test"
whereas export X="test"
directly in shell makes quotes disappear, i.e. echo $X
gives test
why ?
I seem to be executing the same code and it has been messing with my paths :)
Upvotes: 1
Views: 357
Reputation: 159
Given a file test.sh
that contains the phrase export X="test"
the command cat test.sh
outputs the string with escaped double-quotes export X=\"test\"
which evaluates when printed in the bash console as export X="test"
.
Which is why I was under the impression that I executed the same code, however in the first case I was affecting \"test\"
to X
while in the second I was affecting test
to it.
The solution that I first used and then saw elsewhere is to pipe the output of cat
to sed 's/"//g'
, note the single quotes '
instead of double quotes "
.
Thanks to Hendrik Prinsloo for the reference above.
Upvotes: 0
Reputation: 531055
The difference between the two is quote removal. From the man page,
Quote Removal
After the preceding expansions, all unquoted occurrences of the characters \, ', and " that did not result from one of the above expansions are removed.
In $(cat test.sh)
, the eventual command contains unquoted "
characters that did result from a command substitution. The command substitution produced export X="test"
, which splits into the command word export
and its literal argument X="test"
.
In export X="test"
, the command is again export
with an argument X="test"
, but those quotes are unquoted and were not produced by any expansions, so they are removed. The result is the command export
receiving X=test
(not X="test"
) as its argument.
Each export
command then splits its argument on the =
, seeing X
as the variable to define. One sees a right-hand side of test
to use as a value, the other sees "test"
to use as the value, resulting in the different assignments that you observed.
Upvotes: 1