Skip to main content

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 headers #
  2. alias header = 'curl -I'

  3. # find out if remote server supports gzip / mod_deflate or not #
  4. alias 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 别名能够减少输入,请在留言框中分享。

Comments

Popular posts from this blog

OWASP Top 10 Threats and Mitigations Exam - Single Select

Last updated 4 Aug 11 Course Title: OWASP Top 10 Threats and Mitigation Exam Questions - Single Select 1) Which of the following consequences is most likely to occur due to an injection attack? Spoofing Cross-site request forgery Denial of service   Correct Insecure direct object references 2) Your application is created using a language that does not support a clear distinction between code and data. Which vulnerability is most likely to occur in your application? Injection   Correct Insecure direct object references Failure to restrict URL access Insufficient transport layer protection 3) Which of the following scenarios is most likely to cause an injection attack? Unvalidated input is embedded in an instruction stream.   Correct Unvalidated input can be distinguished from valid instructions. A Web application does not validate a client’s access to a resource. A Web action performs an operation on behalf of the user without checking a shared sec

CKA Simulator Kubernetes 1.22

  https://killer.sh Pre Setup Once you've gained access to your terminal it might be wise to spend ~1 minute to setup your environment. You could set these: alias k = kubectl                         # will already be pre-configured export do = "--dry-run=client -o yaml"     # k get pod x $do export now = "--force --grace-period 0"   # k delete pod x $now Vim To make vim use 2 spaces for a tab edit ~/.vimrc to contain: set tabstop=2 set expandtab set shiftwidth=2 More setup suggestions are in the tips section .     Question 1 | Contexts Task weight: 1%   You have access to multiple clusters from your main terminal through kubectl contexts. Write all those context names into /opt/course/1/contexts . Next write a command to display the current context into /opt/course/1/context_default_kubectl.sh , the command should use kubectl . Finally write a second command doing the same thing into /opt/course/1/context_default_no_kubectl.sh , but without the use of k

标 题: 关于Daniel Guo 律师

发信人: q123452017 (水天一色), 信区: I140 标  题: 关于Daniel Guo 律师 关键字: Daniel Guo 发信站: BBS 未名空间站 (Thu Apr 26 02:11:35 2018, 美东) 这些是lz根据亲身经历在 Immigration版上发的帖以及一些关于Daniel Guo 律师的回 帖,希望大家不要被一些马甲帖广告帖所骗,慎重考虑选择律师。 WG 和Guo两家律师对比 1. fully refund的合约上的区别 wegreened家是case不过只要第二次没有file就可以fully refund。郭家是要两次case 没过才给refund,而且只要第二次pl draft好律师就可以不退任何律师费。 2. 回信速度 wegreened家一般24小时内回信。郭律师是在可以快速回复的时候才回复很快,对于需 要时间回复或者是不愿意给出确切答复的时候就回复的比较慢。 比如:lz问过郭律师他们律所在nsc区域最近eb1a的通过率,大家也知道nsc现在杀手如 云,但是郭律师过了两天只回复说让秘书update最近的case然后去网页上查,但是上面 并没有写明tsc还是nsc。 lz还问过郭律师关于准备ps (他要求的文件)的一些问题,模版上有的东西不是很清 楚,但是他一般就是把模版上的东西再copy一遍发过来。 3. 材料区别 (推荐信) 因为我只收到郭律师写的推荐信,所以可以比下两家推荐信 wegreened家推荐信写的比较长,而且每封推荐信会用不同的语气和风格,会包含lz写 的research summary里面的某个方面 郭家四封推荐信都是一个格式,一种语气,连地址,信的称呼都是一样的,怎么看四封 推荐信都是同一个人写出来的。套路基本都是第一段目的,第二段介绍推荐人,第三段 某篇或几篇文章的abstract,最后结论 4. 前期材料准备 wegreened家要按照他们的模版准备一个十几页的research summary。 郭律师在签约之前说的是只需要准备五页左右的summary,但是在lz签完约收到推荐信 ,郭律师又发来一个很长的ps要lz自己填,而且和pl的格式基本差不多。 总结下来,申请自己上心最重要。但是如果选律师,lz更倾向于wegreened,