1

If I do the code:

echo "printf 'working'" | sh

the code prints out working

but when I want to change the current directory this way:

echo "cd ../" | sh

the current directory isn't changed.

Do you know the reason behind that behavior? do you know how to echo cd command to sh in a working way?

Jimmix
  • 5,644
  • 6
  • 44
  • 71

1 Answers1

1
echo "cd /" | sh

actually creates 2 new processes: echo, and sh. The sh process most probably does change the directory, but then just exits. You could test this by

echo "cd ../; touch Jimmix_was_here" | sh
ls -l ../Jimmix_was_here

which should show empty file Jimmix_was_here file, with current timestamp (if you had write permission to the parent directory; otherwise the first command would throw error.)

There's no way to change current directory of a process from within a child; after all if it was possible, it would be a security hole!

Note: this reminds me of a seemingly paradoxical fact: why /bin/cd exists?

Note 2: Try pstree | cat and find both pstree and cat--they are siblings!

Alois Mahdal
  • 10,763
  • 7
  • 51
  • 69
  • 1
    "why /bin/cd exists?" Very good question. I've never thought about that. But there seems to be an answer [here](https://unix.stackexchange.com/questions/50058/what-is-the-point-of-the-cd-external-command) TL;DR POSIX compliance; exit status; automounting a directory – Tim Oct 06 '18 at 17:08