Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check in my bashrc if an alias was already set

Tags:

bash

aliasing

How can I check in my .bashrc if an alias was already set.

When I source a .bashrc file, which has a function name, say fun, and my current environment has an alias as fun also.

I tried unalias fun, but that will give me an error that fun not found when my environment wont have that alias already.

So in my .bashrc, in my fun function I want to check if alias was set, then unalias that.

like image 686
Kumar Alok Avatar asked Mar 20 '12 08:03

Kumar Alok


People also ask

How do I check bash aliases?

How to list existing Bash Alias? You can use the alias -p command to list all the alias currently defined. that contains the list of aliases as created by the Bash alias builtin. $BASH_ALIASES will lose its special properties when being unset.

Which command displays all existing aliases?

We use the compgen -a command to list all the available aliases: $ compgen -a alert egrep fgrep grep l la ll ls ... Here, the -a option tells compgen to list all the aliases.

How do I view an alias file?

To view the alias for a particular name, enter the command alias followed by the name of the alias. Most Linux distributions define at least some aliases. Enter an alias command to see which aliases are in effect. You can delete the aliases you do not want from the appropriate startup file.


2 Answers

If you just want to make sure that the alias doesn't exist, just unalias it and redirect its error to /dev/null like this:

unalias foo 2>/dev/null 

You can check if an alias is set with something like this:

alias foo >/dev/null 2>&1 && echo "foo is set as an alias" || echo "foo is not an alias" 

As stated in the manpage:

For each name in the argument list for which no  value  is  sup- plied,  the  name  and  value  of  the  alias is printed.  Alias returns true unless a name is given for which no alias has  been defined. 
like image 170
mitchnull Avatar answered Sep 28 '22 18:09

mitchnull


Just use the command alias like

alias | grep my_previous_alias 

Note that you can actually use unalias, so you could do something like

[ `alias | grep my_previous_alias | wc -l` != 0 ] && unalias my_previous_alias 

That will remove the alias if it was set.

like image 33
Pablo Fernandez heelhook Avatar answered Sep 28 '22 16:09

Pablo Fernandez heelhook