Last Updated: February 25, 2016
·
1.122K
· sweatypitts

Easy shell script aliases

You want to alias a shell script that you use frequently (or don't because it's too verbose). Here's a quick and easy way to do it.

In your directory of choice, make a directory to hold your scripts. For example, I made a bash directory in my home directory: ~/bash/.

In this directory give each script its own file. I suggest using the extension .sh for clarity, but it is not technically necessary. Here is a trivial example of a shell script file:

#!/bin/bash
SOME_VARIABLE="ls -la"
$SOME_VARIABLE

The first line is the only necessary line. It tells the system which shell to use to execute the script. Bash usually lives in /bin but may not on your machine. The succeeding lines are exactly what you would be manually entering into the shell. Note that variables set in this script will not be set in your shell; they are local to the script.

Then, to give the script an alias, put this in your .bash_profile:

alias name_of_alias="sh /path/to/scripts/script_filename.sh"

The sh command executes the script defined without the file needing to be executable, so don't worry about adding that permission to it.

After saving your .bash_profile enter source ~/.bash_profile into your shell to reload it and you're good to go. Now you can simply enter the alias into your shell and the script will execute.