How to make a permanent zsh alias in command-line?
Asked Answered
S

2

5

I want to permanently store zsh aliases. When I make an alias and shut down ITerm and reopen and it's gone!

alias mkcd="function _mkcd(){mkdir "$1"; cd "$1"} _mkcd"
mkcd Ken
zsh: command not found: mkcd

How can I make it permanent?

Subtend answered 8/5, 2019 at 15:36 Comment(1)
This isn't really important to the question, but regarding your example, Zsh has functionality with the take command (take Ken), and works for nested too: take foo/bar/KenHinze
S
11

Create a file .zshrc in your home directory if it does not exist already and add the alias to the file.

Next time when you open the terminal. It will be available.

To use it in the same session, just source the .zshrc file by running the command . .zshrc from your home directory.

Systematology answered 8/5, 2019 at 15:40 Comment(0)
G
8
  1. Include a line in ~/.zshrc. That's the main configuration file for zsh. Type:
nano ~/.zshrc

and go to the last section of the file. There are examples commented. Copy and edit them (in Nano: alt+a to start selection, alt+6 to copy, ctrl+u to paste).

  1. To add an alias in a separate file (more recommended): Open zsh's folder for such files. It has a variable $ZSH_CUSTOM (equal to $ZSH/custom). Open it:
cd $ZSH_CUSTOM

Create a blank file to hold the aliases:

nano aliases.zsh

It opens the editor. Create an alias like this:

alias <name>=<command>

e.g., alias h='cd ~'

Another option would be to create a variable and use it instead of an alias:

myVar=<value>

e.g., h='~' and using it, for instance, like: cd $h

Now close the editor (ctrl+x for Nano) saving the work (read the text at the bottom). Reload your terminal to bring the changes in effect.

Goulet answered 2/9, 2021 at 5:52 Comment(1)
Seems that approach №2 is not applicable for plain Zsh but requires Oh My Zsh framework installed.Madalena

© 2022 - 2024 — McMap. All rights reserved.