歡迎光臨
每天分享高質量文章

30 個方便的 Bash shell 別名 | Linux 中國

bash 別名(alias)只不過是指向命令的快捷方式而已。
— Nixcraft


本文導航
編譯自 | https://www.cyberciti.biz/tips/bash-aliases-mac-centos-linux-unix.html 
 作者 | Nixcraft
 譯者 | lujun9972

bash 別名alias只不過是指向命令的快捷方式而已。alias 命令允許使用者只輸入一個單詞就執行任意一個命令或一組命令(包括命令選項和檔案名)。執行 alias 命令會顯示一個所有已定義別名的串列。你可以在 ~/.bashrc[1] 檔案中自定義別名。使用別名可以在命令列中減少輸入的時間,使工作更流暢,同時增加生產率。

本文透過 30 個 bash shell 別名的實際案例演示瞭如何建立和使用別名。

bash alias 的那些事

bash shell 中的 alias 命令的語法是這樣的:

  1. alias [alias-name[=string]...]

如何列出 bash 別名

輸入下麵的 alias 命令[2]

  1. alias

結果為:

  1. alias ..='cd ..'

  2. alias amazonbackup='s3backup'

  3. alias apt-get='sudo apt-get'

  4. ...

alias 命令預設會列出當前使用者定義好的別名。

如何定義或者建立一個 bash shell 別名

使用下麵語法 建立別名[3]

  1. alias name =value

  2. alias name = 'command'

  3. alias name = 'command arg1 arg2'

  4. alias name = '/path/to/script'

  5. alias name = '/path/to/script.pl arg1'

舉個例子,輸入下麵命令並回車就會為常用的 clear(清除螢幕)命令建立一個別名 c

  1. alias c = 'clear'

然後輸入字母 c 而不是 clear 後回車就會清除螢幕了:

  1. c

如何臨時性地禁用 bash 別名

下麵語法可以臨時性地禁用別名[4]

  1. ## path/to/full/command

  2. /usr/bin/clear

  3. ## call alias with a backslash ##

  4. \c

  5. ## use /bin/ls command and avoid ls alias ##

  6. command ls

如何刪除 bash 別名

使用 unalias 命令來刪除別名[5]。其語法為:

  1. unalias aliasname

  2. unalias foo

例如,刪除我們之前建立的別名 c

  1. unalias c

你還需要用文字編輯器刪掉 ~/.bashrc 檔案[1] 中的別名定義(參見下一部分內容)。

如何讓 bash shell 別名永久生效

別名 c 在當前登入會話中依然有效。但當你登出或重啟系統後,別名 c 就沒有了。為了防止出現這個問題,將別名定義寫入 ~/.bashrc file[1] 中,輸入:

  1. vi ~/.bashrc

輸入下行內容讓別名 c 對當前使用者永久有效:

  1. alias c = 'clear'

儲存並關閉檔案就行了。系統級的別名(也就是對所有使用者都生效的別名)可以放在 /etc/bashrc 檔案中。請註意,alias 命令內建於各種 shell 中,包括 ksh,tcsh/csh,ash,bash 以及其他 shell。

關於特權許可權判斷

可以將下麵程式碼加入 ~/.bashrc

  1. # if user is not root, pass all commands via sudo #

  2. if [ $UID -ne 0 ]; then

  3.    alias reboot='sudo reboot'

  4.    alias update='sudo apt-get upgrade'

  5. fi

定義與作業系統型別相關的別名

可以將下麵程式碼加入 ~/.bashrc 使用 case 陳述句[6]

  1. ### Get os name via uname ###

  2. _myos="$(uname)"

  3. ### add alias as per os using $_myos ###

  4. case $_myos in

  5.   Linux) alias foo='/path/to/linux/bin/foo';;

  6.   FreeBSD|OpenBSD) alias foo='/path/to/bsd/bin/foo' ;;

  7.   SunOS) alias foo='/path/to/sunos/bin/foo' ;;

  8.   *) ;;

  9. esac

30 個 bash shell 別名的案例

你可以定義各種型別的別名來節省時間並提高生產率。

#1:控制 ls 命令的輸出

ls 命令列出目錄中的內容[7] 而你可以對輸出進行著色:

  1. ## Colorize the ls output ##

  2. alias ls = 'ls --color=auto'

  3. ## Use a long listing format ##

  4. alias ll = 'ls -la'

  5. ## Show hidden files ##

  6. alias l.= 'ls -d . .. .git .gitignore .gitmodules .travis.yml --color=auto'

#2:控制 cd 命令的行為

  1. ## get rid of command not found ##

  2. alias cd..= 'cd ..'

  3. ## a quick way to get out of current directory ##

  4. alias ..= 'cd ..'

  5. alias ...= 'cd ../../../'

  6. alias ....= 'cd ../../../../'

  7. alias .....= 'cd ../../../../'

  8. alias .4= 'cd ../../../../'

  9. alias .5= 'cd ../../../../..'

#3:控制 grep 命令的輸出

grep 命令是一個用於在純文字檔案中搜索匹配正則運算式的行的命令列工具[8]

  1. ## Colorize the grep command output for ease of use (good for log files)##

  2. alias grep = 'grep --color=auto'

  3. alias egrep = 'egrep --color=auto'

  4. alias fgrep = 'fgrep --color=auto'

#4:讓計算器預設開啟 math 庫

  1. alias bc = 'bc -l'

#4:生成 sha1 數字簽名

  1. alias sha1 = 'openssl sha1'

#5:自動建立父目錄

mkdir 命令[9] 用於建立目錄:

  1. alias mkdir = 'mkdir -pv'

#6:為 diff 輸出著色

你可以使用 diff 來一行行第比較檔案[10] 而一個名為 colordiff 的工具可以為 diff 輸出著色:

  1. # install colordiff package 🙂

  2. alias diff = 'colordiff'

#7:讓 mount 命令的輸出更漂亮,更方便人類閱讀

  1. alias mount = 'mount |column -t'

#8:簡化命令以節省時間

  1. # handy short cuts #

  2. alias h = 'history'

  3. alias j = 'jobs -l'

#9:建立一系列新命令

  1. alias path = 'echo -e ${PATH//:/\\n}'

  2. alias now = 'date +"%T"'

  3. alias nowtime =now

  4. alias nowdate = 'date +"%d-%m-%Y"'

#10:設定 vim 為預設編輯器

  1. alias vi = vim

  2. alias svi = 'sudo vi'

  3. alias vis = 'vim "+set si"'

  4. alias edit = 'vim'

#11:控制網路工具 ping 的輸出

  1. # Stop after sending count ECHO_REQUEST packets #

  2. alias ping = 'ping -c 5'

  3. # Do not wait interval 1 second, go fast #

  4. alias fastping = 'ping -c 100 -s.2'

#12:顯示開啟的埠

使用 netstat 命令[11] 可以快速列出服務區中所有的 TCP/UDP 埠:

  1. alias ports = 'netstat -tulanp'

#13:喚醒休眠的伺服器

Wake-on-LAN (WOL) 是一個乙太網標準[12],可以透過網路訊息來開啟伺服器。你可以使用下麵別名來快速啟用 nas 裝置[13] 以及伺服器:

  1. ## replace mac with your actual server mac address #

  2. alias wakeupnas01 = '/usr/bin/wakeonlan 00:11:32:11:15:FC'

  3. alias wakeupnas02 = '/usr/bin/wakeonlan 00:11:32:11:15:FD'

  4. alias wakeupnas03 = '/usr/bin/wakeonlan 00:11:32:11:15:FE'

#14:控制防火牆 (iptables) 的輸出

Netfilter 是一款 Linux 作業系統上的主機防火牆[14]。它是 Linux 發行版中的一部分,且預設情況下是啟用狀態。這裡列出了大多數 Liux 新手防護入侵者最常用的 iptables 方法[15]

  1. ## shortcut for iptables and pass it via sudo#

  2. alias ipt = 'sudo /sbin/iptables'

  3. # display all rules #

  4. alias iptlist = 'sudo /sbin/iptables -L -n -v --line-numbers'

  5. alias iptlistin = 'sudo /sbin/iptables -L INPUT -n -v --line-numbers'

  6. alias iptlistout = 'sudo /sbin/iptables -L OUTPUT -n -v --line-numbers'

  7. alias iptlistfw = 'sudo /sbin/iptables -L FORWARD -n -v --line-numbers'

  8. alias firewall =iptlist

#15:使用 curl 除錯 web 伺服器 / CDN 上的問題

  1. # get web server essay-headers #

  2. alias essay-header = 'curl -I'

  3. # find out if remote server supports gzip / mod_deflate or not #

  4. alias essay-headerc = 'curl -I --compress'

#16:增加安全性

  1. # do not delete / or prompt if deleting more than 3 files at a time #

  2. alias rm = 'rm -I --preserve-root'

  3. # confirmation #

  4. alias mv = 'mv -i'

  5. alias cp = 'cp -i'

  6. alias ln = 'ln -i'

  7. # Parenting changing perms on / #

  8. alias chown = 'chown --preserve-root'

  9. alias chmod = 'chmod --preserve-root'

  10. alias chgrp = 'chgrp --preserve-root'

#17:更新 Debian Linux 伺服器

apt-get 命令[16] 用於透過因特網安裝軟體包 (ftp 或 http)。你也可以一次性升級所有軟體包:

  1. # distro specific - Debian / Ubuntu and friends #

  2. # install with apt-get

  3. alias apt-get= "sudo apt-get"

  4. alias updatey = "sudo apt-get --yes"

  5. # update on one command

  6. alias update = 'sudo apt-get update && sudo apt-get upgrade'

#18:更新 RHEL / CentOS / Fedora Linux 伺服器

yum 命令[17] 是 RHEL / CentOS / Fedora Linux 以及其他基於這些發行版的 Linux 上的軟體包管理工具:

  1. ## distrp specifc RHEL/CentOS ##

  2. alias update = 'yum update'

  3. alias updatey = 'yum -y update'

#19:最佳化 sudo 和 su 命令

  1. # become root #

  2. alias root = 'sudo -i'

  3. alias su = 'sudo -i'

#20:使用 sudo 執行 halt/reboot 命令

shutdown 命令[18] 會讓 Linux / Unix 系統關機:

  1. # reboot / halt / poweroff

  2. alias reboot = 'sudo /sbin/reboot'

  3. alias poweroff = 'sudo /sbin/poweroff'

  4. alias halt = 'sudo /sbin/halt'

  5. alias shutdown = 'sudo /sbin/shutdown'

#21:控制 web 伺服器

  1. # also pass it via sudo so whoever is admin can reload it without calling you #

  2. alias nginxreload = 'sudo /usr/local/nginx/sbin/nginx -s reload'

  3. alias nginxtest = 'sudo /usr/local/nginx/sbin/nginx -t'

  4. alias lightyload = 'sudo /etc/init.d/lighttpd reload'

  5. alias lightytest = 'sudo /usr/sbin/lighttpd -f /etc/lighttpd/lighttpd.conf -t'

  6. alias httpdreload = 'sudo /usr/sbin/apachectl -k graceful'

  7. alias httpdtest = 'sudo /usr/sbin/apachectl -t && /usr/sbin/apachectl -t -D DUMP_VHOSTS'

#22:與備份相關的別名

  1. # if cron fails or if you want backup on demand just run these commands #

  2. # again pass it via sudo so whoever is in admin group can start the job #

  3. # Backup scripts #

  4. alias backup = 'sudo /home/scripts/admin/scripts/backup/wrapper.backup.sh --type local --taget /raid1/backups'

  5. alias nasbackup = 'sudo /home/scripts/admin/scripts/backup/wrapper.backup.sh --type nas --target nas01'

  6. alias s3backup = 'sudo /home/scripts/admin/scripts/backup/wrapper.backup.sh --type nas --target nas01 --auth /home/scripts/admin/.authdata/amazon.keys'

  7. 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'

  8. 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'

  9. 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'

  10. 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'

  11. alias amazonbackup =s3backup

#23:桌面應用相關的別名 - 按需播放的 avi/mp3 檔案

  1. ## play video files in a current directory ##

  2. # cd ~/Download/movie-name

  3. # playavi or vlc

  4. alias playavi = 'mplayer *.avi'

  5. alias vlc = 'vlc *.avi'

  6. # play all music files from the current directory #

  7. alias playwave = 'for i in *.wav; do mplayer "$i"; done'

  8. alias playogg = 'for i in *.ogg; do mplayer "$i"; done'

  9. alias playmp3 = 'for i in *.mp3; do mplayer "$i"; done'

  10. # play files from nas devices #

  11. alias nplaywave = 'for i in /nas/multimedia/wave/*.wav; do mplayer "$i"; done'

  12. alias nplayogg = 'for i in /nas/multimedia/ogg/*.ogg; do mplayer "$i"; done'

  13. alias nplaymp3 = 'for i in /nas/multimedia/mp3/*.mp3; do mplayer "$i"; done'

  14. # shuffle mp3/ogg etc by default #

  15. alias music = 'mplayer --shuffle *'

#24:設定系統管理相關命令的預設網絡卡

vnstat 一款基於終端的網路流量檢測器[19]dnstop 是一款分析 DNS 流量的終端工具[20]tcptrack 和 iftop 命令顯示[21] TCP/UDP 連線方面的資訊,它監控網絡卡並顯示其消耗的頻寬。

  1. ## All of our servers eth1 is connected to the Internets via vlan / router etc ##

  2. alias dnstop = 'dnstop -l 5 eth1'

  3. alias vnstat = 'vnstat -i eth1'

  4. alias iftop = 'iftop -i eth1'

  5. alias tcpdump = 'tcpdump -i eth1'

  6. alias ethtool = 'ethtool eth1'

  7. # work on wlan0 by default #

  8. # Only useful for laptop as all servers are without wireless interface

  9. alias iwconfig = 'iwconfig wlan0'

#25:快速獲取系統記憶體,cpu 使用,和 gpu 記憶體相關資訊

  1. ## pass options to free ##

  2. alias meminfo = 'free -m -l -t'

  3. ## get top process eating memory

  4. alias psmem = 'ps auxf | sort -nr -k 4'

  5. alias psmem10 = 'ps auxf | sort -nr -k 4 | head -10'

  6. ## get top process eating cpu ##

  7. alias pscpu = 'ps auxf | sort -nr -k 3'

  8. alias pscpu10 = 'ps auxf | sort -nr -k 3 | head -10'

  9. ## Get server cpu info ##

  10. alias cpuinfo = 'lscpu'

  11. ## older system use /proc/cpuinfo ##

  12. ##alias cpuinfo='less /proc/cpuinfo' ##

  13. ## get GPU ram on desktop / laptop##

  14. alias gpumeminfo = 'grep -i --color memory /var/log/Xorg.0.log'

#26:控制家用路由器

curl 命令可以用來 重啟 Linksys 路由器[22]

  1. # Reboot my home Linksys WAG160N / WAG54 / WAG320 / WAG120N Router / Gateway from *nix.

  2. alias rebootlinksys = "curl -u 'admin:my-super-password' 'http://192.168.1.2/setup.cgi?todo=reboot'"

  3. # Reboot tomato based Asus NT16 wireless bridge

  4. alias reboottomato = "ssh admin@192.168.1.1 /sbin/reboot"

#27:wget 預設斷點續傳

GNU wget 是一款用來從 web 下載檔案的自由軟體[23]。它支援 HTTP,HTTPS,以及 FTP 協議,而且它也支援斷點續傳:

  1. ## this one saved by butt so many times ##

  2. alias wget = 'wget -c'

#28:使用不同瀏覽器來測試網站

  1. ## this one saved by butt so many times ##

  2. alias ff4 = '/opt/firefox4/firefox'

  3. alias ff13 = '/opt/firefox13/firefox'

  4. alias chrome = '/opt/google/chrome/chrome'

  5. alias opera = '/opt/opera/opera'

  6. #default ff

  7. alias ff =ff13

  8. #my default browser

  9. alias browser =chrome

#29:關於 ssh 別名的註意事項

不要建立 ssh 別名,代之以 ~/.ssh/config 這個 OpenSSH SSH 客戶端配置檔案。它的選項更加豐富。下麵是一個例子:

  1. Host server10

  2. Hostname 1.2.3.4

  3. IdentityFile ~/backups/.ssh/id_dsa

  4. user foobar

  5. Port 30000

  6. ForwardX11Trusted yes

  7. TCPKeepAlive yes

然後你就可以使用下麵陳述句連線 server10 了:

  1. $ ssh server10

#30:現在該分享你的別名了

  1. ## set some other defaults ##

  2. alias df = 'df -H'

  3. alias du = 'du -ch'

  4. # top is atop, just like vi is vim

  5. alias top = 'atop'

  6. ## nfsrestart - must be root ##

  7. ## refresh nfs mount / cache etc for Apache ##

  8. 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'

  9. ## Memcached server status ##

  10. alias mcdstats = '/usr/bin/memcached-tool 10.10.27.11:11211 stats'

  11. alias mcdshow = '/usr/bin/memcached-tool 10.10.27.11:11211 display'

  12. ## quickly flush out memcached server ##

  13. alias flushmcd = 'echo "flush_all" | nc 10.10.27.11 11211'

  14. ## Remove assets quickly from Akamai / Amazon cdn ##

  15. alias cdndel = '/home/scripts/admin/cdn/purge_cdn_cache --profile akamai'

  16. alias amzcdndel = '/home/scripts/admin/cdn/purge_cdn_cache --profile amazon'

  17. ## supply list of urls via file or stdin

  18. alias cdnmdel = '/home/scripts/admin/cdn/purge_cdn_cache --profile akamai --stdin'

  19. alias amzcdnmdel = '/home/scripts/admin/cdn/purge_cdn_cache --profile amazon --stdin'

總結

本文總結了 *nix bash 別名的多種用法:

☉ 為命令設定預設的引數(例如透過 alias ethtool='ethtool eth0' 設定 ethtool 命令的預設引數為 eth0)。
☉ 修正錯誤的拼寫(透過 alias cd..='cd ..'讓 cd.. 變成 cd ..)。
☉ 縮減輸入。
☉ 設定系統中多版本命令的預設路徑(例如 GNU/grep 位於 /usr/local/bin/grep中而 Unix grep 位於 /bin/grep 中。若想預設使用 GNU grep 則設定別名 grep='/usr/local/bin/grep' )。
☉ 透過預設開啟命令(例如 rmmv 等其他命令)的互動引數來增加 Unix 的安全性。
☉ 為老舊的作業系統(比如 MS-DOS 或者其他類似 Unix 的作業系統)建立命令以增加相容性(比如 alias del=rm)。

我已經分享了多年來為了減少重覆輸入命令而使用的別名。若你知道或使用的哪些 bash/ksh/csh 別名能夠減少輸入,請在留言框中分享。


via: https://www.cyberciti.biz/tips/bash-aliases-mac-centos-linux-unix.html

作者:nixCraft[24] 譯者:lujun9972 校對:wxy

本文由 LCTT 原創編譯,Linux中國 榮譽推出

LCTT 譯者

lujun9972 ? ? ? ?
共計翻譯:72 篇
貢獻時間:49 天


推薦文章

< 左右滑動檢視相關文章 >

點選圖片、輸入文章 ID 或識別二維碼直達

贊(0)

分享創造快樂

© 2024 知識星球   網站地圖