Shell基础
1. Shell概述
1.1 shell是什么
Shell是一个命令行解释器,它为用户提供了以向Linux内核发送请求以便运行程序的界面系统级程序,用户可以用Shell来启动,挂起,停止甚至是编写一些程序.
1.2 shell的分类
- Bourne家族,主要包括:sh,ksh,Bash,psh,zsh.
- C家族,主要包括:csh,tcsh
2. 脚本的执行方式
2.1 前提
- echo输出命令:
echo [选项] [内容]
选项: -e 支持反斜线控制的字符转换
控制字符 | 作用 |
---|---|
\\ | 输出 \ 本身 |
\a | 输出警告音 |
\b | 退格键,也就是左删除键 |
\c | 取消输出行尾的换行符,和"-n"选项一致 |
\e | ESCAPE键 |
\f | 换页符 |
\n | 换行符 |
\r | 回车键 |
\t | 制表符 |
\v | 垂直制表符 |
\ Onnn | 按照八进制ASCII码表输出字符,其中0为数字零,nnn是三位八进制数 |
\xhh | 按照十六进制ASCII码表输出字符,其中hh是两位十六进制数 |
实例:
#支持反斜线控制的字符转换
[root@li ~]# echo -e 'ab\bc'
ac
[root@li ~]# echo -e 'a\tb\tc\nd\te\tf'
a b c
d e f
#不支持反斜线控制的字符转换
[root@li ~]# echo 'ab\bc'
ab\bc
[root@li ~]# echo 'a\tb\tc\nd\te\tf'
a\tb\tc\nd\te\tf
2.2 第一个脚本
vi helloworld
#!/bin/bash
#The first program
#Author: Doug Li
echo -e "This\tis\nDougLi\nfirst\tShell\tProgram"
2.3 脚本执行
- 赋予执行权限,直接运行
[root@li ~]# chmod +755 helloword.sh
[root@li ~]# ./helloword.sh
- 通过bash调用执行脚本(有无执行权限均可)
[root@li ~]# bash helloword.sh
- 格式转换dos2unix,unix2dos
3. bash的基本功能
3.1 历史命令与命令补全
3.1.1 历史命令
history [选项] [历史命令保存文件]
选项:
-c: 清空历史命令
-w: 把缓存中的历史命令写入历史命令保存文件
历史命令保存文件: ~/.bash_history
默认保存条数: /etc/profile 中的HISTSIZE=1000
历史命令的调用
- 使用上下箭头调用以前的历史命令
- 使用"!n" 重复执行第n条历史命令
- 使用"!!"重复执行上一条命令
- 使用"!字符串"重复执行最后一条以该字符串开头的命令
[root@li ~]# history | head -10
1 cd /etc/sysconfig/network-scripts/
2 ll
3 vi ifcfg-eno16777736
4 reboot
5 du -sh
6 df -h
7 docker pull hub.c.163.com/public/ubuntu:18.04
8 docker images
9 docker images -a
10 docker images --all=true
[root@li ~]# !2
ll
总用量 32
-rw-------. 1 root root 926 7月 27 11:49 anaconda-ks.cfg
-rwxr-xr-x 1 root root 98 8月 17 13:41 helloword.sh
-rwxr-xr-x. 1 root root 210 7月 27 14:37 python:3
-rwxr-xr-x 1 root root 18681 8月 17 13:45 Tetris.sh
[root@li ~]# !!
ll
总用量 32
-rw-------. 1 root root 926 7月 27 11:49 anaconda-ks.cfg
-rwxr-xr-x 1 root root 98 8月 17 13:41 helloword.sh
-rwxr-xr-x. 1 root root 210 7月 27 14:37 python:3
-rwxr-xr-x 1 root root 18681 8月 17 13:45 Tetris.sh
3.1.2 命令与文件补全
在bash中,命令与文件补全是非常方便与常用的功能,我们只要输入命令或文件时,按"Tab"键就会自动进行补全
3.2 命令别名与常用快捷键
3.2.1 命令别名
设定命令别名:alias 别名=‘原命令’
</
查询命令别名:alias