Home > OS >  How do you set an alias in zsh on Mac OS
How do you set an alias in zsh on Mac OS

Time:08-08

I've set a zsh alias like this:

alias sed="/usr/local/Cellar/gnu-sed/4.8/bin/gsed"

I can confirm it is working by running:

type sed
sed is an alias for /usr/local/Cellar/gnu-sed/4.8/bin/gsed

However, if I put exactly the same code, alias setting and type sed then in a script under the file name test and run it get the default sed:

zsh test
sed is /usr/bin/sed

I've also tried it with extending PATH and still get the same thing which puzzles me...

CodePudding user response:

If you want to use the command word sed as gsed in all your future scripts (which if you really want to do, you can do this), Homebrew has info on how to achieve this, at the end of the installation for brew install gsed:

GNU "sed" has been installed as "gsed".
If you need to use it as "sed", you can add a "gnubin" directory
to your PATH from your bashrc like:

    PATH="/opt/homebrew/opt/gnu-sed/libexec/gnubin:$PATH"

Though you are asking about zsh so I'm assuming you've upgraded to at least macOS Catalina and are now trying to use zsh instead of bash, so that means I would suggest putting the suggested line from Homebrew into ~/.zshrc instead of ~/.bashrc.

Some things have changed, the default Homebrew installation directory is now, well you can use the command brew --prefix to get your directory, it's now currently /opt/homebrew instead of the old /usr/local/Cellar.

Now your sed should run as gsed in all your scripts.

Additional notes

Reasons why your code involving aliases isn't working as expected and some additional notes to take away (speaking to zsh and bash):

  1. Aliases in a script file disappear after the script has been run (unless the script is called by another script, then the calling script has the new alias definition).
  2. Aliases executed in startup files like "~/.zshrc" etc. aren't used within script files.

CodePudding user response:

The only thing that worked for me was to create a function. After that sed was overriden with gsed when I called the help argument

#!/bin/bash
sed () {
    /usr/local/Cellar/gnu-sed/4.8/bin/gsed "$@"
}
sed --help
  • Related