简体   繁体   中英

Linux difference between when to use parentheses

Why do I get extra empty line when running 2). To me 1 is like 2. So why the extra line in 2)?

1)

export p1=$(cd $(dirname $0) && pwd)
#                                  ^
echo p1

2)

export p2=$(cd $(dirname $0)) && pwd
#                           ^
echo p2 

p1 captures the output of cd (empty) and pwd .

p2 only captures the output of cd , and then runs pwd without redirection.


echo p1 prints a literal p1 (with a newline). I guess you didn't actually copy-paste from your terminal, but instead typed in some thing else.


peter@tesla:~$ export p2=$(true) && pwd
/home/peter
peter@tesla:~$ echo "x${p2}x"
xx

cd in a subshell doesn't affect the parent shell's pwd, so I just substituted the true command to make it more readable.

$echo $0
/bin/bash
$ echo $(cd $(dirname $0) && pwd)
/bin
$ echo $(cd $(dirname $0)) && pwd

/home/user
$

In the 1st expression it becomes echo $(cd /bin && pwd) . Therefore the inner 2 commands execute in a subshell and return back the pwd value which is then echoed.

In the 2nd expression it gets reduced to echo $(cd /bin) && pwd . Therefore only the cd command executes in a subshell and returns nothing to echo (hence by default echo just prints an empty line). Since echo ran successfully(exit code=0) && results in true and pwd cmd is run in current shell and pwd gets printed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM