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
$()
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.