8

I have access to a couple of remote accounts, which I mount via sshfs in subdirs of $HOME/SSHFS. In order to remind me that I'm not working with local files, I have set $PROMPT_COMMAND to a function prmt_cmd, where I set a different $PS1 if $PWD matches $HOME/SSHFS*. Now, to add a little extra protection, I'd like to add the -i flags automatically to the rm, mv and cp commands whenever I'm in a subdir of $HOME/SSHFS. So I ended up with something like

function prmt_cmd () {
if [[ $PWD == $HOME/SSHFS* ]] ; then
    PS1=some prompt
    alias rm='rm -I'
    alias mv='mv -i'
    alias cp='cp -i'
else
    # Reset the PS1, remove aliases
    PS1=my default prompt
    unalias rm mv cp
fi
}

(In the actual definition, I do some other stuff, but this is irrelevant.) However, unalias complains when the aliases do not exist, meaning that I get three error messages before each prompt when I'm not in SSHFS/*. unalias doesn't seem to have a switch to silence it. So my question is: Is there a better way to achieve what I want? Maybe I'm simply Doing It (Completely) Wrong.

In case it's relevant, $BASH_VERSION = 4.1.5(1)-release on Ubuntu 10.10.

3 Answers 3

14

Just redirect the output.

unalias rm mv cp >/dev/null 2>/dev/null
2
  • 4
    &>/dev/null will take out both birds with one stone.
    – Travis
    Sep 12, 2015 at 4:18
  • 2
    just redirect stderr is sufficient 2>/dev/null Aug 23, 2019 at 15:59
2

In bash you could do the following to unalias an alias only if it exists, for example rm:

[ -n "`alias -p | grep '^alias rm='`" ] && unalias rm

Another idea would be to overwrite the alias, even it if exists:

alias rm='/bin/rm'
0

alias name >/dev/null 2>&1 && unalias name

Instead of redirecting the output of unalias, this quietly tests for the presence of the alias, then deletes it if found.

This avoids aborting a script running set -e, unless something actually goes wrong doing the unalias. It also does not eat the diagnostic message from unalias when something does go wrong.

It is also simpler than parsing the output of alias -p with child processes.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .