Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you set an alias in zsh on macOS? [closed]

Tags:

macos

zsh

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 filename 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.

like image 537
t11 Avatar asked Dec 21 '25 19:12

t11


2 Answers

Open your terminal and run the command:

  1. touch .zshrc
  2. open ~/.zshrc

Paste your alias on the editor like below - and save it.

alias runner="dart run build_runner build --delete-conflicting-outputs"
alias dev="flutter run --flavor dev -t lib/main_development.dart"

If the file already has other things in it, that's fine. You can put it at the end.

like image 63
Hadiuzzaman Avatar answered Dec 24 '25 09:12

Hadiuzzaman


To answer the question in the title, "How do you set an alias in zsh on Mac OS," the syntax in the question is correct. For example

alias gst="git status"

As you would expect, now when I enter gst, it runs git status

The reason it didn't work with the test script is because of how it was run. The zsh test command creates a new zsh shell, and aliases do not transfer to new shells/sub-shells, unlike environment variables. Functions also do not transfer to new shells, so that doesn't help.

If you source the script file instead, it will run the commands in the file in the current shell instead of creating a new one. Then the sed alias will work. So, instead of zsh test, do this

source test

The common solution is Hadiuzzaman's answer: put alias commands in ~/.zshrc. Whenever, a new z-shell is created, using zsh for example, the commands in ~/.zshrc are executed in the newly created shell, so your aliases will always be available in z-shells. But, if you want them in bash shells, too, you need to put them in ~/.bashrc. Since the syntax for aliases are the same for bash and zsh, I put mine in a separate file, ~/.aliases, and then put source .aliases in my ~/.zshrc and ~/.bashrc files. That way I only need to update one file instead of two.

like image 31
bjc Avatar answered Dec 24 '25 11:12

bjc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!