6

I have a folder with chmod 000 permissions on it with a lot of different stuff in, the way I get in is a start bash in sudo by running sudo bash.

Why can't I do &&? I want to cd into the directory with one command like this:

sudo bash && cd desktop

When I run this, I am still in ~ which is the default directory.

I have to run this instead

sudo bash
cd desktop

Also, the desktop is not the folder, its a subfolder of desktop, but it doesn't matter. It's the same thing anyways.

DisplayName
  • 11,688

2 Answers2

18

The part after && is executed in the current shell, it is not some argument handed over to the bash you run with sudo.

You might be tempted to try

sudo bash -c 'cd desktop'

but that doesn't work because that bash exits after cd desktop.

You can try:

sudo sh -c 'cd desktop && exec bash'

which "works" (i.e. places you in the directory desktop in a Bash shell with uid=0). I'd rather issue the two separate commands than that one liner.

Anthon
  • 79,293
  • Your answer is 100% correct, except you (IMHO) miss the point of the OP’s confusion. I believe the key point of the answer to this question is that sudo bash runs the privileged shell in a new, separate process, and that the “current” (primary) shell doesn’t handle the cd command until the (secondary) privileged shell exits. I suspect that the OP is looking at sudo bash && cd desktop as if it were analogous to set -x && cd desktop. – G-Man Says 'Reinstate Monica' Oct 13 '14 at 19:04
2

It does work, just not how you expect. && waits until the command before it completes. If the result at that point is true, it will execute the next instruction. So if you type bash && cd desktop, you will first be presented with a bash shell. If you type exit, you'll be back in whatever shell you were in before, and then the directory will change to the desktop folder.

In terms of the functionality I described, sudo is inconsequential. Your use case for sudo is probably not best practice, and you should consider other solutions.

craq
  • 149