0

I'm trying to remove an alias set to the keyword clear in zsh, but first i would like to check if it exists. here is what i've tried:

if whence -w clear | grep "alias" then
  unalias clear
fi

but I can't figure out how to make if work with the output of the piline.

Luan Vitor
  • 83
  • 6
  • 2
    Does this answer your question? [why in an 'if' statement 'then' has to be in the next line in bash?](https://stackoverflow.com/questions/57834136/why-in-an-if-statement-then-has-to-be-in-the-next-line-in-bash) (The question mentions Bash, but the answer applies to `sh` in general, including Zsh) – that other guy Jul 17 '20 at 20:40
  • @LuanVitor: Aside from the missing semicolon in your code, the `if` is unnecessary: If the alias exists, you want to remove it, if it doesn't exist, it doesn't matter if you try to remove it. Hence, I would not use an `if` at all, but simply write `unalias clear 2>/dev/null || true`. The sole purpose of using `|| true` is to allow your code to run even if `set -e` is in effect. – user1934428 Jul 20 '20 at 09:24

1 Answers1

0

Did you forget a semicolon after grep "alias"? The following works just fine in zsh.

% alias clear=something
% alias
clear=something
% if whence -w clear | grep "alias"; then
      unalias clear
  fi
  clear: alias
% alias
%
Mark Paine
  • 1,874
  • 13
  • 14
  • thaks it works now, although I am certain i tested whith the semicolon. it's there a way to hide the output of the grep thing? if i have it in this way in .zshrc it prints "clear: alias" in every new shell – Luan Vitor Jul 17 '20 at 22:38
  • just appending `>/dev/null 2&>1` before ';' fixes it – Luan Vitor Jul 17 '20 at 22:53
  • 1
    `grep -q "alias"`, but there's no need for `grep` at all. `if alias clear > /dev/null; then unalias clear; fi` or `alias clear > /dev/null && unalias clear`. – chepner Jul 19 '20 at 14:03
  • Or skip the check altogether and just ignore the error if `unalias clear` fails. – chepner Jul 19 '20 at 14:05
  • 1
    @LuanVitor : For hiding the output of `grep`, I wouldn't use redirection (which also would hide error messages), but would simply use `grep -Fq`. – user1934428 Jul 20 '20 at 09:26