1

When I try to execute ls|more, the command works perfectly, however when I try to save the command in a variable like x='ls|more' and then execute it using $x I get the following error :

ls: cannot access |: No such file or directory
ls: cannot access more: No such file or directory

Why?

1 Answer 1

5

When you execute

ls|more

the shell parses that line and understands the three tokens to be the command ls followed by a pipe, followed by the command more. When you execute

$x

the shell expands that variable but does not parse the result, at least not in the same way. It will split the contents of the variable at white space, take the first sequence of characters to be a command name, and the following sequences of characters to be arguments. So it will understand ls|more to be the command ls|more and ls | more to be the command ls followed by the arguments | and more, which ls takes to be file names.

To get the shell to reparse the contents of that variable, use eval, like this:

eval "$x"
3
  • While you were accepting my answer, I was editing it to try to do a better job of answering "Why?"
    – garyjohn
    Oct 15, 2013 at 6:24
  • Shouldn't the argument to eval be quoted? Note, that variables can contain any characters including newlines and word-splitting before eval would change meaning in such cases.
    – Jan Hudec
    Oct 15, 2013 at 6:59
  • @JanHudec: I think you're right. Thank you. I edited my answer to add the quotes.
    – garyjohn
    Oct 15, 2013 at 7:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .