Search code examples
bashzshaliasconditional-operatorzsh-alias

Bash Alias with ternary?


Still dipping my toes in bash coding and trying to crate a 1 liner alias to:

  • if 'perms' is entered w/out a parameter, it does a stat -c '%a - %n' *
  • else if 'perms' is entered with a parameter it does stat -c '%a - %n' <parameter>
  • Goal is if no param added, shows perms for all files/folders, else show perms for specified file/folder.

I've gotten this far with 2 different versions, but they both result in the same thing; WITH a parameter added it works fine; without a parameter it isn't getting the * added and the command says it requires a parameter. So for some reason the "if true" part is not filling the $a var, but the "else" part does fill it.

alias perms="a=$(if [ -z '$@' ]; then *; else $@; fi) stat -c '%a - %n' $a"

alias perms="a=$([[ -z '$1' ]] && '*' || $1) stat -c '%a - %n' $a"

Solution

  • This should be a function. (Most things people try to use aliases for should be functions.)

    perms () {
      if [ $# -eq 0 ]; then
        stat -c '%a -%n' *
      else
        stat -c '%a - %n' "$@"
      fi
    }