Create Bash Aliases

Bash is the default shell on OS X and Linux systems, and used by most command line users. Bash has a great feature that lets you create a keyword to associate with a command. It’s a great way to make it easy to execute hard to type commands. It’s called alias.

As you start to customize your workflow, you start to find ways to reduce your keystrokes while getting more done. You can create an alias at any time on the command line. That’s great, because it less you adapt quickly. One thing to know is that because it’s part of your current session, it’ll go away when you exit the shell. If you want an alias to persist, put it in your ~/.bashrc so that it gets created when you start a new shell.

Here’s an example alias. This seems a little too simple, but it’s a surprisingly popular alias. do a search for ‘dotfiles’ on github. A lot of people have it in their .bashrc.

alias ll='ls -l'

If you want to see a list of your current aliases:

$ alias

If you want to remove an alias, use the unalias command and the appropriate

$ unalias ll

Anyway, what’s happening her is the keyword ll is associated with the ls -lcommand. When the user types ll as a command line, Bash replaces it with ls -l, then runs the command. While this an easy example, an alias
becomes more useful as the command it represents becomes longer and more
complicated to type or remember.

The value of the alias can also be multiple commands piped together. Hard-coded parameters are also ok. Because of the way the substitution works, you can’t pass an argument to an alias.

Here’s an example hard-coded parameters. typing weather at the bash prompt, will connect you to the weather service.

alias weather='telnet 3000'

Here’s a few examples using multiple commands

# Show files in Finder that start with a dot '.'
alias show="defaults write AppleShowAllFiles -bool true && killall Finder"

# Hide files in Finder that start with a dot '.'
alias hide="defaults write AppleShowAllFiles -bool false && killall Finder"

# List only directories
alias lsd='ls -l | grep "^d"'

One thing to remember about the lsd alias is that since you can pass an argument to ls, this alias only works on the current directory.

Sorry, but comments are closed. I hope you enjoyed the article