ZSH Alias Last Command and Alias + Persist commands

Introduction

If you find yourself constantly running the same long commands on your terminal, setting up quick aliases can be a game-changer. This blog post will walk you through creating two handy ZSH functions that allow you to define and save aliases on-the-fly. With these, you can alias any command, including the last command you ran, without even leaving the terminal!


1. Create Aliases On-the-Fly

First up, let's talk about how you can instantly create aliases for any given command.

Code Snippet:

add_alias() {
  alias_name="$1"
  alias_command="$2"
  aliases_file="$HOME/.zsh_aliases"

  # Create alias and save to the current session
  alias "$alias_name=$alias_command"

  # Append the alias to zsh_aliases file for persistence
  echo "alias $alias_name=\"$alias_command\"" >> "$aliases_file"

  # Source the zsh_aliases file to apply changes
  source "$aliases_file"

  echo "Alias $alias_name added."
}

 

Usage:

Place this function in your .zshrc file or another file that's sourced by it. Then add source $HOME/.zsh_aliases in your .zshrc to load these aliases in future sessions.

add_alias ll "ls -la"

Now, ll will be an alias for ls -la, and it will also be saved in your .zsh_aliases file for future use.


2. Alias the Last-Run Command

Ever ran a command and immediately realised you want to alias it? This function has got you covered.

Code Snippet:

# Obviously feel free to name this command whatever you like. Same for the one above.
alias_last_command() {
  alias_name="$1"
  last_command=$(fc -ln -1)
  last_command="${last_command##*( )}"
  aliases_file="$HOME/.zsh_aliases"

  if [ -z "$alias_name" ]; then
    echo "Alias name is required."
    return 1
  fi

  # Create the alias and save to the current session
  alias "$alias_name=$last_command"

  # Append the alias to .zsh_aliases file for persistence
  echo "alias $alias_name=\"$last_command\"" >> "$aliases_file"

  # Source the .zsh_aliases file to apply changes
  source "$aliases_file"

  echo "Alias $alias_name for '$last_command' added."
}

Usage:

Just like the previous function, add this to your .zshrc and make sure you're sourcing the .zsh_aliases file.

To create an alias for the last command you ran:

alias_last_command ll

This will make ll an alias for whatever your last command was, saving it in .zsh_aliases for future sessions.


Conclusion

With these two ZSH functions, you can quickly and conveniently set up aliases right from your terminal, making your workflow much more efficient. Give them a try and watch your productivity soar!

Happy coding! 🚀