Creating new aliases from the terminal

Wed, Jul 26, 2023 2-minute read

If you are in the terminal enough, creating aliases from the command line is a great way to save time and be more productive.

You can type:

$ alias ll='ls -la'

but if you want these to stick around beyond the current session, you need to add it to your aliases file.

You can do this by creating a bash function that writes to your aliases file, and then making an alias for that function. Here’s how you can do it:

Firstly, open your ~/.bashrc or ~/.bash_profile and add the following lines to the end of the file:

alias newalias='function _newalias() { echo "alias $1=\"$2\"" >> ~/.aliases; source ~/.aliases; unset -f _newalias; }; _newalias'

You also need to ensure that your aliases file is sourced when a new shell is started. Add this to your ~/.bashrc or ~/.bash_profile:

if [ -f ~/.aliases ]; then
    source ~/.aliases
fi

Now, let’s break down what’s happening:

  • alias newalias=... sets up the alias newalias to the following command.
  • function _newalias() {...}; _newalias is a temporary function that is immediately called. This structure is necessary because aliases can’t accept arguments directly.
  • echo "alias $1=\"$2\"" >> ~/.aliases; creates the new alias in the .aliases file. The $1 and $2 represent the first and second arguments you pass to newalias.
  • source ~/.aliases; updates your current shell with the new alias.
  • unset -f _newalias; removes the function definition after it’s used.

After saving and closing your file, you need to source your .bashrc or .bash_profile for the changes to take effect. You can do this by running source ~/.bashrc or source ~/.bash_profile.

With this setup, you can create new aliases directly from the command line. For example:

newalias "l" "ls -l"

This command would create an alias named l that runs ls -l, and save it to your ~/.aliases file.