-1

I have met a question when using cd command in a script. here is the test below, so, could anyone help to tell the reason?

why does not "/bin/sh cd /root/eos/" work ,but "/bin/sh -c ls && cd /root/eos/" works well in centos thanks.

[root@izbp16eo65uiwii1mfm63tz eos]# pwd
/root/testeosnode/CryptoKylin-Testnet/docker/eos
[root@izbp16eo65uiwii1mfm63tz eos]# /bin/sh  cd /root/eos/
[root@izbp16eo65uiwii1mfm63tz eos]# pwd
/root/testeosnode/CryptoKylin-Testnet/docker/eos
[root@izbp16eo65uiwii1mfm63tz eos]# /bin/sh -c ls &&  cd /root/eos/
build.log  build.sh  Dockerfile  eos
[root@izbp16eo65uiwii1mfm63tz eos]# pwd
/root/eos

env CentOS Linux release 7.5.1804 (Core) [root@izbp16eo65uiwii1mfm63tz eos]# ls -l /bin/sh lrwxrwxrwx 1 root root 4 10oct 9 18:00 /bin/sh -> bash

Harry Ma
  • 143
  • 3
  • 1
    `/bin/sh cd /root/eos/` will give you `/bin/sh: 0: Can't open cd` – hek2mgl Nov 27 '18 at 12:58
  • 1
    It's all about the definition of "works". "Works" != "shows the expected output" – in the latter case, the problem might be the expectations. – glglgl Nov 27 '18 at 13:09

1 Answers1

3

/bin/sh cd /root/eos/ does not work because that's not the proper way to have /bin/sh execute a command.

/bin/sh -c ls works because the -c argument will make /bin/sh execute the next argument, which is ls.

/bin/sh -c "cd /root/eos/" would "work". It will run /bin/sh , that process will change its directory to /root/eos and then that process will exit, leaving the working directory of your running shell unaffected.

/bin/sh -c ls && cd /root/eos/ is the combination of 2 commands.

First /bin/sh -c ls is executed. If that succeeds, cd /root/eos is executed. Note that the /bin/sh command only runs ls. It does not run cd /root/eos - that part is run by the current shell of yours, and will change your working directory.

Note that this is also different from doing:

/bin/sh -c "ls && cd /root/eos"

In thats case /bin/sh will run the entire ls && cd /root/eos command - though as the cd command only affects the process started with the /bin/sh command, it will not affect the shell you are running this in.

nos
  • 223,662
  • 58
  • 417
  • 506