0

Today I noticed an interesting difference between executing an command using sudo or as root.

Using sudo rm -rf /opt/nextcloud/* will not delete folders

vagrant@collab:~$ sudo rm -rf /opt/nextcloud/*
vagrant@collab:~$ sudo ls /opt/nextcloud/
nextcloud  nextcloud-16.0.4

When I first become root and then execute the command, the folders are deleted

vagrant@collab:~$ sudo su -
root@collab:~# rm -rf /opt/nextcloud/*
root@collab:~# sudo ls /opt/nextcloud/
root@collab:~# 

Why is this? What is the correct way to delete the folders using sudo?

2
  • What are the flags & owners on the folders?
    – xenoid
    Nov 17, 2019 at 9:50
  • I've got the habit of doing ls before rm -rf, in order to visualize what I'm going to delete.
    – simlev
    Nov 17, 2019 at 11:08

1 Answer 1

2

The command sudo rm -rf /opt/nextcloud/* is interpreted by the shell running as your regular user. The shell tries to expand * before sudo even runs. If for some reason * cannot be expanded, then the command becomes:

  • either sudo rm -rf /opt/nextcloud/* where sudo (and then rm) gets /opt/nextcloud/* literally with the literal * and no further expansion occurs; this is POSIX behavior; /opt/nextcloud/* obviously does not exist.
  • or sudo rm -rf in some circumstances (e.g. in Bash when the nullglob option is set).

There are other possibilities (e.g. compare failglob in Bash) but they seem not to match your case.

In any case the -f option of rm gets relevant. It means

-f
Do not prompt for confirmation. Do not write diagnostic messages or modify the exit status in the case of no file operands, or in the case of operands that do not exist. […]

(source)

Effectively you provided an "operand that does not exist" or "no file operands", so the command did nothing and succeeded silently.


My hypothesis is the non-elevated shell couldn't expand /opt/nextcloud/* because the regular user has no read permissions on /opt/nextcloud/. Another possibility is you made a typo in /opt/nextcloud/* and didn't spot this because there was no error message. There was no error message because this is how rm -f works.

sudo ls /opt/nextcloud/ involves no expansion by the shell. The command run ls as root. The ls itself had access to the specified directory and its content, therefore it worked.

After sudo su - you were in a shell running as root. This shell was able to expand /opt/nextcloud/*, so rm -rf /opt/nextcloud/* worked as you expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.