Linux Bash笔记

这里主要记录Linux系统的默认shell Bash用法.

快捷键

CTRL + l  # clear
set -o emacs #默认模式
set -o vi 
bind -P  # 查看当前绑定

当前命令编辑

  • Ctrl + A : 光标移到开头
  • Ctrl + E : 光标移到结尾
  • Ctrl + U : 删除整行
  • Ctrl + W : 删除前一个单词
  • Ctrl + k : 删除至行末

历史命令

  • Ctrl + R : 历史命令查找
  • Ctrl + p : 上一条历史命令
  • Ctrl + n : 下一条历史命令
  • Ctrl + z : 挂起命令,fg继续前台执行
  • ^old^new : 替换上一个命令字符串
  • sudo !! : sudo执行上一个命令
  • Alt + . : 打印上一个命令的最后参数
  • !$ : 特殊变量,代表上一个命令的最后参数

目录切换

  • cd - : 切换到上一个工作目录
  • cd ~ : 切换到Home目录

关于dirs,pushd,popd命令的用法参加此文.

Enable Tab Completion

cp /etc/skel/.bashrc ~/  
sudo apt-get install --reinstall bash-completion  

Bash特定用法

环境变量

  • 临时环境变量: export myname=xulz
  • 永久环境变量
    • 用户环境变量:~/.bashrc, ~/.bash_profile
    • 系统环境变量: /etc/bashrc, /etc/profile, /etc/environment

注:

  • 变量名不允许包含-和空格
  • Linux系区分大小写,Windows不区分
    # Linux
    vi ~/.profile
    vi ~/.bash_profile
    export PATH="/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    # Mac
    vi /etc/paths

加载顺序:

  • /etc/environment
  • /etc/profile
  • /etc/bash.bashrc
  • /etc/profile.d/test.sh
  • ~/.profile :登录时读取
  • ~/.bashrc

shebang

    #!/bin/bash
    # 脚本执行时告诉shell用哪个程序解释脚本
#! /bin/bash -xe

# -x 执行详细脚本, 等同于   set -x, 可用于调试目的
# -e 遇到非0错误立即退出, 等同于   set -e

重定向/管道

2>&1
# 1 代表 stdout, 2 代表 stderr.
# 2>1 可以看做重定向 stderr 到 stdout.实际上被解释为 "重定向 stderr 到文件名为 1的文件". 
# & 指出接下来是一个文件描述符而不是一个文件

一些例子

# stdout 写入文件,终端不可见
command > output.txt

# 错误信息会写入文件
command 2>> output.txt
# 标准输出和错误会写入文件
command &> output.txt

# stdout copy to file,终端仍可见
command | tee output.txt
# 文件追加
command | tee -a output.txt

# stdout and stderr copy to file
command |& tee output.txt

制作包含二进制数据的安装脚本

参考1/2

Troubleshooting

tab 不能自动补全?

sudo dpkg-reconfigure dash 选择no (原因: 默认创建的新用户使用的dash)

sh脚本异常:/bin/sh^M:bad interpreter: No such file or directory

:set ff=unix

bash忽略错误

rm -f nonesuch
rm -rf my/dir || true