tags:

views:

143

answers:

2

Hi guys,

I'm learning ksh, I'm trying to run a command using a subshell, but I got different results, I'm guessing the reason.

root@setPrompt[/home/za] X=$("ls -ltr")
ksh: ls -ltr:  not found.
root@setPrompt[/home/za] X=$('ls -ltr')
ksh: ls -ltr:  not found.
root@setPrompt[/home/za] X="$(ls -ltr)"
root@setPrompt[/home/za] echo $X
total 5256 -rw-

thanks

A: 

It probably didn't inherit the environment. If the path is not set then it can't find the ls program

Jay
This problem has nothing to do with the environment or path. jamessan's answer is correct in that it has everything to do with quoting rules, parameter expansion, and command substitution.
jabbie
+2  A: 

$() runs the enclosed command in a subshell and returns its output. Your first two examples are trying to run the command "ls -ltr". Since you've quoted the entire command, the shell is going to look for a command whose entire name ls -ltr, not one whose name is ls and is being passed the options -ltr. The third example runs the command ls, with the argument -ltr and X gets the output of that command. Since the $() was enclosed by double-quotes, field splitting and pathname expansion are not performed.

An example of the difference:

$ ls
bin
$ echo $(echo 'b*')
bin
$ echo "$(echo 'b*')"
b*

See also the SUS specification for command expansion.

jamessan
Thanks for the explanation
jhon