shell基础和通配符、命令补全、命令别名、history、输入输出重定向
shell 基础
- shell是一个命令解释器,提供用户和机器之间的交互
- 支持特定的语法,比如逻辑判断、循环
- 每个用户都可以有自己的shell
- centos7默认shell为bash(Bourne Agin Shell)
-
还有zsh ksh等
-
查看当前shell
echo $SHELL
echo $0 #不是所有shell都支持,centos7 sh不支持
env | grep SHELL
cat /etc/passwd | grep username
ps #查看当前shell
echo $$
ps -ef | grepecho $$
| grep -v ps | grep -v grep -
cat /etc/shells #查看当前可以使用的shell
FTP用户我们会不让他有登入shell的权限所以把shell设置成/sbin/nologin,此时生效还需要把、/sbin/nologin加入到/etc/shells
中(或者是/usr/sbin/shell)
命令历史
- history命令 上下方向键控制history
- 命令历史存在家目录.bash_history中
- echo $HISTSIZE #查看hostory存最多多少条命令
- history -c #清除当前内存命令历史,但是.bash_history文件不会删除
- 每次要当用户退出当前shell命令历史才会被写入到.bash_history文件中
- 设置HISTSIZE配置文件在/etc/profile中,修改后source /etc/profile或者重新登录shell中
- 格式化history输出
HISTTIMEFORMAT="%Y/%m/%d %H:%M:%S "
当前生效加入到/etc/profile中永久生效 - 禁止删除.bash_history文件 `chattr +a .bash_history #只可以追加内容
- !! #上一条命令
- !n #运行history中第n条命令
- !mkdir #运行最近mkdir命令
命令补全及别名
- TAB键 1下或2下补全,有多个相同补全内容需要敲击2下
- centos7中可以自动补全参数 需要安装`bash-completion安装后需要重启系统
- 命令别名设置
alias tt='touch test'
在shell中之间输入alias进行别名设置退出shell后不会保存,需要自定义别名永久保存需要在家目录.bashrc文件中设置,
修改后执行source .bashrc
重新加载配置文件
还有写配置文件可能在/etc/bashrc中或者在/etc/profile.d/中unlias tt
进行取消命令别名
通配符
- ls .txt #``任意多个字符
-
ls ?.txt #
?
1个字符 -
touch {1,2,5}
[test@xujb01 test]$ touch {1,2,5} [test@xujb01 test]$ ll 总用量 0 -rw-r--r--. 1 test sudo_test_group 0 11月 16 06:37 1 -rw-r--r--. 1 test sudo_test_group 0 11月 16 06:37 2 -rw-r--r--. 1 test sudo_test_group 0 11月 16 06:37 5
-
ls [0-3].txt #匹配0-3中的一个.txt文件 不能touch
输入输出重定向
- cat 1.txt > 2.txt #把1.txt内容重定向到2.txt 覆盖
- cat 1.txt >> 2.txt #把1.txt内容追加到2.txt中
- cat 1.txt 2> 2.txt #默认cat 1.txt > 2。txt是把标准输出重定向到2.txt,如果命令错误是不会重定向到2.txt的,此命令就是
把标准错误输出重定向到2.txt,例如如果1.txt不存在则把返回的错误信息重定向到2.txt,标准输出则不会写入[test@xujb01 test]$ cat 1.txt 2> 2.txt [test@xujb01 test]$ cat 2.txt cat: 1.txt: 没有那个文件或目录
- cat 1.txt > 2.txt 2>&1 #标准输出和标准错误输出都重定向到2.txt中
- cat > 2.txt < 1.txt #把文件1.txt内容重定向到2.txt中
标准输入
linux shell下常用输入输出操作符是:
- 标准输入 (stdin) :代码为 0 ,使用 < 或 << ; /dev/stdin -> /proc/self/fd/0 0代表:/dev/stdin
- 标准输出 (stdout):代码为 1 ,使用 > 或 >> ; /dev/stdout -> /proc/self/fd/1 1代表:/dev/stdout
- 标准错误输出(stderr):代码为 2 ,使用 2> 或 2>> ; /dev/stderr -> /proc/self/fd/2 2代表:/dev/stderr
*注:<<EOF
表示标准输入以EOF
进行输入结束
[test@xujb01 test]$ cat > test <<EOF
> hello world
> nihao
> EOF
[test@xujb01 test]$ cat test
hello world
nihao