0

In my .bashrc I alias bat if it is installed with [ -f /usr/bin/bat ] && alias cat='bat -pp'

This works fine, but if bat gets uninstalled, the alias becomes broken, so I was trying to make the alias do the check at runtime, but the below is broken. How can I test for bat inside the alias?

alias cat='if [ -f /usr/bin/bat ]; then bat -pp $@; else /usr/bin/cat $@; fi'
YorSubs
  • 3,194
  • 7
  • 37
  • 60
  • 4
    Alias can't take parameters. Use a function instead. – choroba Sep 19 '21 at 16:12
  • 1
    Note that there are a lot of people in the linked duplicate who claim that aliases _can_ take parameters, but those people are misunderstanding how their own code works; their "demonstrations" don't show what they claim that they do. `set -- "first argument" "second argument"; alias testAlias='echo "$1"; #'; testAlias "Other String"` is an instructive example, insofar as it disproves their arguments, showing that `$1` does not expand to the alias's own parameter list. – Charles Duffy Sep 19 '21 at 17:06

1 Answers1

3

but if bat gets uninstalled

It's not like you uninstall stuff all the time. I would do instead:

if hash bat 2>/dev/null; then
   alias cat='bat -pp'
fi

Anyway, use a function.

cat() {
   if hash bat 2>/dev/null; then
        bat -pp "$@"
   else
        command cat "$@"
   fi
}
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • Oh, I thought my question was a bit useless when people pointed out that I need a function, but your answer is very interesting I think. Why do you use `hash` instead of `which` (I've never used that command before)? And this `command` command, that tells is to use a non-alias reference? Really curious how `hash` and `command` work in your answer! – YorSubs Sep 19 '21 at 18:24
  • 1
    `Why do you use hash instead of which` https://stackoverflow.com/questions/592620/how-can-i-check-if-a-program-exists-from-a-bash-script `his command command, that tells is to use a non-alias reference?` Yes, it tells not to use the function `cat`, otherwise it would call itself, endless loop. `how hash and command work` https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Bourne-Shell-Builtins – KamilCuk Sep 19 '21 at 20:05
  • 1
    Fascinating, thanks for this info, will be very useful for me I think! – YorSubs Sep 19 '21 at 20:07