0

I have a directory /var/opt/gitlab/backups with the following permissions:

[user@localhost ~]$ sudo ls -la /var/opt/gitlab/backups
total 1316296
drwx------.  2 git  root         63 1月  21 21:44 .
drwxr-xr-x. 21 root root       4096 1月  21 21:39 ..
-rw-------.  1 git  git  1347880960 1月  21 21:44 1642819457_2022_01_21_14.1.2-ee_gitlab_backup.tar

Now the following command does not remove anything

sudo rm -rf /var/opt/gitlab/backups/*

While the following command removes the directory and everything inside

sudo rm -rf /var/opt/gitlab/backups/

Also the following command will remove the specific file

sudo rm -rf /var/opt/gitlab/backups/1642819457_2022_01_21_14.1.2-ee_gitlab_backup.tar

It's only the file wildcard way does not work (which unfortunately is what I want)

However what I want is only removing the files inside and not removing the directory. I suspect it's because of the permission settings but changing the permissions is not an option for me. The directory owner and permissions are set automatically by a third-party software and I would like not to mess around.

Is there any way to achieve the "removing all files inside the directory but not the directory itself" effect?

cr001
  • 105

1 Answers1

4

Wildcards are expanded by your shell. In order for

rm /var/opt/gitlab/backups/*

to work, then you must have permission to list the contents of /var/opt/gitlab/backups/. Consider for example as a non-root user I run this command:

$ echo /var/*
/var/cache /var/db /var/empty /var/lib /var/lock /var/log /var/mail /var/run /var/spool /var/svc.d /var/tmp

Then the shell expands the * to the list of non-hidden files in that directory, then echo prints those values.

However, if I try to do the same thing with a directory that I don't have the ability to access:

$ echo /root/*
/root/*

The shell doesn't have permission to enumerate the content, and therefore cannot expand the *.

If you really must use the wildcard, then you can try:

$ sudo /bin/sh -c 'rm -rf /var/opt/gitlab/backups/*'

With that, you run a new shell (/bin/sh) as root. That shell will have permission to read the content of the directory and can expand * to the contents.

Andy Dalton
  • 13,993