0

Hoi everybody,

I am currently struggling with having to execute multiple commands in an echo. The following line is an example of the problem I am having:

echo (cd .. && pwd)

The idea is, that, when I am currently in the folder "home/Documents", the above code prints "home" - but is still in the directory "home/Documents". However, the above command fails.

The more general question is: How can I execute multiple commands in an echo and print the last result (or all results if its not possible any other way).

Thank you and kind regards.

bublitz
  • 101

2 Answers2

2

The idea is, that, when I am currently in the folder home/Documents, the above code prints home - but is still in the directory home/Documents

You don't need echo at all because pwd prints what you want. Use this:

(cd .. && pwd)

There are two smart things here:

  • (whatever) runs whatever in a subshell. If cd is inside these parentheses, it will change the current working directory of the subshell, not the main (your current) shell.
  • a && b runs b iff a succeeded (returned exit status 0). In general, if you want your script using cd to be robust, it's good to always check if cd succeeded. This prevents running other command(s) in a wrong directory.

Note when there are symlinks involved, you may not get the path you expect. See this community wiki answer for details.

-1

I found the solution:

(cd .. && echo `pwd`)

Thank you :)

bublitz
  • 101