Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to define "conditional" aliases in shell

What's the best way to define an alias if, let's say, "ag" executable is found?

if (( $+commands[ag] )) ; then alias grep='ag'; fi

or

[[ -s $(which ag) ]] && alias grep='ag'

or

if $(which ag >& /dev/null); then alias grep='ag'; fi

or ...?

By best, I mean more robust, more performant and/or more portable (Bash, Zsh).

What's your advice?

like image 331
user3341592 Avatar asked Dec 21 '15 08:12

user3341592


People also ask

Which shells support aliases?

Please note that the alias command is built into a various shells including ksh, tcsh/csh, ash, bash and others.

What does == mean in shell script?

== is a bash-specific alias for = and it performs a string (lexical) comparison instead of a numeric comparison.

Where do I put shell aliases?

You need to put bash shell aliases in the ~/. bashrc file ($HOME/. bashrc) file executed by bash for non-login shells. On most modern Linux distros, you may want to put all your bash alias definitions into a separate file like ~/.


1 Answers

I don't see how the simple obvious POSIX variant would have any drawbacks compared to the (mostly non-portable) alternatives you propose.

type ag >/dev/null 2>&1 && alias grep=ag
like image 149
tripleee Avatar answered Oct 17 '22 07:10

tripleee