0

I want to make alias for:

  • rm -rf * => #rm -rf *
  • rm * => #rm *

When I type rm -rf *, I want it to be commented out and not take action.

[Q] General question is can we make generate aliases for the commands with parameters?

alper
  • 469

1 Answers1

1

You cannot create alias with spaces, i.e. something like below is invalid:

alias 'rm -rf *'='#rm -rf *'

But of course you can create alias for commands with parameters:

alias foo='#rm -rf *'

Although from the examples from your question, looks like you want to put # before every rm. To do so, you need to only alias rm:

alias rm='#rm'

If you wanted to only "disable" rm for -rf, then you would need to write a wrapper function:

rm() {
    if [ "$1" != "-rf" ]; then
        rm $@
    fi
}

Can I disable only for rm -rf * but keeping other rm -rf if * is not included?

Yes, you can. For example:

rm() {
    if [ "$1" != "-rf" ]; then
        rm $@
    else
        shift 1
        x="$@"
        if [ "$x" != "$(echo *)" ]; then
            rm -rf $@
        fi
    fi
}
  • Can I disable only for rm -rf * but keeping other rm -rf if * is not included? – alper Jul 13 '20 at 17:16
  • Yes, you can do that –  Jul 13 '20 at 17:29
  • Can I generate this function in ZSH, it gives following error: zsh: parse error near()'` – alper Jul 13 '20 at 17:34
  • I've just tested it in Zsh and it works –  Jul 13 '20 at 18:17
  • Should I paste it directly into terminal or into .bashrc and call it? – alper Jul 13 '20 at 20:11
  • Neither. If you paste into terminal, you will get it only for the current session. To make it "permanent" you need to put it into configuration file. You want to have it in Zsh, so the file would be .zshrc (.bashrc is for Bash) –  Jul 13 '20 at 20:50
  • If I make the function name rmm() { I don't get the error , but instead if its rm() the parse error shows up – alper Jul 14 '20 at 00:00
  • @alper I may require a new question "Why Zsh gives a parse error for my wrapper for rm?" –  Jul 14 '20 at 00:13
  • Sure: https://unix.stackexchange.com/questions/598418/why-zsh-gives-a-parse-error-for-my-wrapper-for-rm – alper Jul 14 '20 at 10:10