Can anyone tell me how to interpret this:
listpage="ls |more" (the spaces are there in the example)
$listpage
It's from my bash book and I'm not sure what it means
Can anyone tell me how to interpret this:
listpage="ls |more" (the spaces are there in the example)
$listpage
It's from my bash book and I'm not sure what it means
I hope that's an example of how not to do something because it doesn't work.
listpage="ls | more"
$listpage
ls: cannot access "|": no such file or directory
ls: cannot access "more": no such file or directory
The idea, I think, is to run the ls command to list the current directory, and feed its output into the more program so you can view it page by page. But you can't dump that text into a variable and expect it to work because the shell doesn't evaluate variables that way unless you force it to with eval.
How I'd actually do that is this:
alias listpage="ls | more"
listpage
Actually it's part of the section on the eval command (which I'm not sure I understand). I guess I just should have asked what the statement
$listpage
means -- does it mean to display the value of listpage, and if so, why didn't it use the echo command?
Think more literally. It's just a variable, and the shell does the same thing with variables for every statement whether they're at the beginning of the line or the end. For each statement, the shell
1) Splits apart on semicolons or pipes, and evaluates each part(turns variables into their contents, etc).
2) Executes each part.
CMD="echo"
$CMD asdf
will print 'asdf' because it
1) converts $CMD asdf into echo asdf
2) runs "echo asdf".
Now this:
CMD="ls | more"
$CMD
does this:
1) Converts $CMD into ls | more
2) Executes ls | more
See something wrong? Pipes were supposed to be handled in step 1 but weren't, because it was in a variable. Step 2 doesn't do anything to pipes, so just feeds it into ls raw. ls complains there's no such files "|" and "more".
Now this:
CMD="ls | more"
eval "$CMD"
1) Converts eval "$CMD" into eval "ls | more"
2) Executes eval "ls | more"
, shoving the string "ls | more" back into step 1.
1) Splits ls | more
into two statements, ls and more
2) Executes ls, piping it into more.
eval's just a special keyword that bumps the shell back into step 1.