Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want sudo to allow me to run a command when my current working directory is, for example, /tmp. Example usage is removing files from /tmp directory, so I am in /tmp ($PWD of shell == /tmp), then I can run, rm -v someuseless.bin (someuseless.bin of course not belongs to me, so I can't remove it). If it is impossible (I can't find references in sudo manuals), then why? Maybe there is a security violation that I did not spotted here. Thanks.

share|improve this question
I'd also usggest looking after linux ACLs. – mveroone Aug 24 '14 at 10:56

You can definitely embed the $cwd in sudoers, to allow someone only to remove a file under a particular directory, but you're going the wrong way about it. The way to do what you want is to use absolute paths in sudoers, eg

orc       ALL=(ALL) /bin/rm /tmp/someuseless.bin
share|improve this answer
Is $cwd here a shell variable, or something related to sudoers? The second way I just using now (embedding absolute paths), but there is no only /tmp directory that I want to use in that way (some other directory with four of five levels of names, so it is long to type it) – user141301 Oct 16 '12 at 12:57
It's shell shorthand for "the current working directory". The way you were using is the right way; you're going to have to list out all the working directories you want to be valid anyway, so there's no harm in listing them in the sudo'ed commands list. – MadHatter Oct 16 '12 at 13:01

You can write a shell script which checks for the current directory, then give sudo rights to run that script.



if [ "$CWD" != "/tmp" ]; then
   exit 1

echo do your stuff


user       ALL=(ALL) /usr/local/bin/

But beware doing this is dangerous, as now you need to check also if all arguments are ok (for example, the user might be in /tmp, but run 'rm -rf /').

The best way is to do as MadHatter told, explicitly add the paths the user is allowed to remove, or as Kwaio suggested, set ACLs on the directories.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.