内容提纲
Shell
- 本机上有哪些可执行的shell命令:cd /bin ;ls
- 命令提示符:$(普通用户) 或 #(root用户)
- echo ‘abc’ 输出显示字符串abc
- exit n:退出,设置退出码为n。
- echo -n: -n 不换行
- echo -e: -e 转义特殊字符
- read -p “sdfsfs” n:-p,允许在read命令行中直接指定一个提示,输入值直接绑定到变量n
- read -t 30 :30s内输入才有效
全局系统变量
- HOME:
- USER:
- PATH:
小试身手
第一个shell脚本
#!/bin/bash
echo "hello word"
目前index.sh并不具备可执行的权限(x),应授与执行权限 chmod a+x ./index.sh
- 运行脚本:./index.sh (或者 /bin/bash index.sh)
交互接收终端输入参数
#!/bin/bash
read PERSON
echo "hello $PERSON"
read 命令从 stdin 获取输入并赋值给变量
常用读写文件
echo
- echo ‘string’ 打印字符串string
- echo ‘string’ > 文件:文件不存在,则创建文件并写入 string
- echo ‘string’ >> 文件:在文件尾部追加字符串string
cat
- cat file: 打印file的内容
- cat file1 > file2 :把file1内容复制到file2
- cat file1 >> file2 :把file1内容复制追加到file2
#!/bin/bash
path="./tmp.log"
path2="./tmp.log2"
if [ ! -f ${path2} ]; then
cat ${path} > ${path2}
else
cat ${path} >> ${path2}
fi
shell变量
- 定义变量:
- name=value
- name=‘value’
- declare 核心语法:
- -i 声明为整数
- -a 声明未数组
- -f 声明未函数
- -r 声明未只读
- 使用变量
- $name
- ${name} 更严谨,明确变量边界
- 有两种方式可以将命令输出赋值给变量:
- 反引号字符(`)
- ( e x p r e s s i