2.1 KiB
Custom Commands
Optimize repetitive terminal tasks. Custom commands, or aliases, create shortcuts for long or frequently used commands.
Creating an Alias
Consider a common scenario: checking web server connections with a lengthy netstat command:
netstat -plant | grep '80\|443' | grep -v LISTEN | wc -l
Typing this repeatedly is inefficient. Create an alias as a shortcut. For example, let conn execute this command.
alias conn="netstat -plant | grep '80\|443' | grep -v LISTEN | wc -l"
Now, simply type conn:
conn
You'll get the same output.
Enhance it with an informative message:
alias conn="echo 'Total connections on port 80 and 443:' ; netstat -plant | grep '80\|443' | grep -v LISTEN | wc -l"
Running conn will now yield:
Total connections on port 80 and 443:
12
Note: Aliases created this way are temporary. They disappear when your terminal session ends.
Making Aliases Permanent
Aliases are session-bound by default. To make them permanent, add them to your shell's profile file. For Bash, this is typically ~/.bashrc.
Open ~/.bashrc (or create it if it doesn't exist):
nano ~/.bashrc
Add your alias to the end of the file:
alias conn="echo 'Total connections on port 80 and 443:' ; netstat -plant | grep '80\|443' | grep -v LISTEN | wc -l"
Save and exit.
Apply changes without restarting your terminal:
source ~/.bashrc
Now, your custom command conn will be available in all new and sourced terminal sessions.
Listing Aliases
To view all active aliases in your current shell, simply run:
alias
This helps in troubleshooting command behavior.
Conclusion
Aliases are powerful tools for optimizing your terminal workflow, offering quick command shortcuts. While full Bash scripts offer more complexity, aliases provide an immediate, user-level solution without requiring root access for installation.
{notice} This content was inspired by a piece by softwareshinobi on Dev Team Six.