Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 5 down vote accepted

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"
share|improve this answer
    
While you were accepting my answer, I was editing it to try to do a better job of answering "Why?" –  garyjohn Oct 15 '13 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 '13 at 6:59
    
@JanHudec: I think you're right. Thank you. I edited my answer to add the quotes. –  garyjohn Oct 15 '13 at 7:12

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.