1

I want to set .bashrc to check a specified command and ask for confirmation before execution.

For example, I want to set command 'rm' in .bashrc to receive a question before execution started otherwise being terminated.

read -p "Type password? " pass
if [ "$pass" = "1234" ]; then
  // do the execution
else
  // Termination and echo a message wrong pass. 
fi

Example:

> rm MyFile.txt
 Type password? ****
You have successfully removed MyFile.txt
>
1

1 Answer 1

2

You can define an alias or a function which will take precedence over the binary looked up from $PATH when resolving rm :

rm() {
    read -p "Type password? " pass
    if [ "$pass" = "1234" ]; then
         command rm "$@"
    else
         #Termination and echo a message wrong pass. 
    fi
}

Note that this doesn't constitute a reasonable security measure as it is very easily avoided by using command rm, \rm or the path to the rm binary (usually /bin/rm) instead of calling rm.

9
  • 1
    @YesThatIsMyName that works for every command. Do you mean you want a single piece of code that will intercept every command, check if it's in a list then conditionnally execute some code?
    – Aaron
    Commented Aug 29, 2019 at 9:24
  • I am pretty sure that this is what he wants. Adding 8 lines for every command is not an elegant way to solve his problem. I mean, he may also do this by changing access rights of the executables, but he wants a nice .bashrc solution. Commented Aug 29, 2019 at 9:31
  • The code doesn't work. The error: syntax error near unexpected token `fi'. Plus, it is fine if for every executable command e.g. (ls, rm, cd, ...etc) to write many lines of codes, but I just need it to work properly.
    – jesy2013
    Commented Aug 29, 2019 at 10:23
  • I couldn't edit the comment so I am adding a new one. The code works for rm() but not ls(). Can it be adapted to work for any shell command?
    – jesy2013
    Commented Aug 29, 2019 at 10:33
  • It works just fine for me with ls, maybe you have an alias defined for ls? What does type ls output in your modified environment?
    – Aaron
    Commented Aug 29, 2019 at 10:59

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