0

I have been using Linux for two years, but today I encountered a very strange thing. I have nginx deployed on one server, and this is its log folder:

♪ log l -d nginx drwx------ 2 nginx nginx 4.0K Dec 7 03:15 nginx

(I'm using zsh and ♪ log means I am in a folder named 'log'. As you can see, I ended up saying that I did not go into the folder named 'nginx'.)

When I try to access it:

♪ log cd nginx cd: permission denied: nginx ♪ log sudo cd nginx ♪ log

Even after I changed its permissions to 766, this folder still can not be accessed:

♪ log sudo chmod -R 766 nginx ♪ log l -d nginx drwxrw-rw- 2 nginx nginx 4.0K Dec 7 03:15 nginx ♪ log cd nginx cd: permission denied: nginx ♪ log sudo cd nginx ♪ log

Can someone explain this to me?

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232

2 Answers2

3

The main reason is that sudo cd nginx entered the nginx folder and exited. So you are back to the previous state before launching the sudo command.

It's the same than doing sudo ls nginx/* for exemple which will list the content of the nginx folder and exit.

sudo spawns a new process with the requested privileges and running the requested command. Once the command finish, sudo exits and you fall back to previous situation.

To dig more, you have to understand that your location inside a file system, is dynamically managed by the shell program you are using. When a process is forked the shell context is replicated in the new process. Every manipulation of the copied context is specific to it, and is not affecting the parent context. So in our case, cd nginx is modifying the $PWD of the new process and not the parent's one. Once it finish, the related context is destroyed and then, you fallback in the parent's context which wasnt modified.

As the other dude explained to you, to be able to move into a folder you need to also have the execution permission (+x).

netmonk
  • 1,870
2

A user has to have execute permissions on a directory to be able to change to it.

See e.g. the question "To cd into a directory".

To change to the directory as your ordinary user (not nginx or root), you will first have to sudo chmod o+x nginx. You may also start a root shell with sudo -s and access it from that shell session.


sudo cd nginx doesn't make much sense. The cd will succeed, but as soon as the sudo process exits, you will be left in the directory from where you executed sudo. The current working directory is part of the process' environment, and a child process (sudo) can't change the environment of its parent (your interactive shell).

Kusalananda
  • 333,661