sherlock
sherlock

Reputation: 2807

Why isn't bash splitting fields inside $() operator?

Just for the sake of learning, while I was trying a bunch of stuff, I noticed a bash behavior that I couldn't logically explain.

$ ls $(echo a)
ls: cannot access 'a': No such file or directory

$ ls $($'\145\143\150\157\40\141')
echo a: command not found

$ ls $($"\145\143\150\157\40\141")
\145\143\150\157\40\141: command not found

In the first case, echo a was being evaluated to a which becomes an argument to ls. Fair enough. However, in the second case, the octal encoded string was being evaluated to echo a as expected; but the entire string was being treated as the command by $(). Moreover, in the third case, no expansion is taking place with double quotes. Why don't the fields split? I guess it has got something to do with field splitting in bash. But, I failed to explain what could the exact problem be. Is there any way I can make the field splitting work so that it gets treated like the first case?

Upvotes: 1

Views: 91

Answers (1)

oguz ismail
oguz ismail

Reputation: 50795

A word of the form $'string' is expanded to a single-quoted string, as if the dollar sign had not been present. That means,

$($'\145\143\150\157\40\141')

is the same as

$('echo a')

And single-quoted strings don't undergo word splitting or any other kind of expansion. See Bash Reference Manual § ANSI-C Quoting.

Is there any way I can make the field splitting work so that it gets treated like the first case?

$ ls $(eval $'\145\143\150\157\40\141')
ls: cannot access 'a': No such file or directory

This is inadvisable though, see BashFAQ#048.


Concerning $"string" syntax, see Bash Reference Manual § Locale-Specific Translation, it's whole another thing.

Upvotes: 5

Related Questions