目录
一、shell script里常用的几个命令
1、expr命令
这个命令可以对整数表达式进行运算。注意,运算符前后必须要有空格符
[hyxy@master ~]$ expr 1 + 2
3
[hyxy@master ~]$ expr 12 - 10
2
[hyxy@master ~]$ expr 3 \* 4 <==乘号需要转义字符进行转义
12
[hyxy@master ~]$ expr 6 / 4 <==只能进行整除运算
1
[hyxy@master ~]$ expr `expr 3 + 9` / 3 <== 嵌套或者是给变量赋值时,使用反单引号
4
[hyxy@master ~]$ n=3
[hyxy@master ~]$ m=9
[hyxy@master ~]$ result=`expr \`expr $n + $m \` / 4` <==反单引号嵌套时要使用转义字符
[hyxy@master ~]$ echo $result
3
或者使用选项可以对字符串进行一些计算
[hyxy@master ~]$ expr index "hello linux" ol <==计算匹配字符第一次出现的位置序号,从1开始哦
3
[hyxy@master ~]$ expr substr "hello linux" 2 3 <==截取字符串,从第2个开始截取,截取3个长度
ell
[hyxy@master ~]$ expr length "hello linux" <==计算字符串的长度
11
[hyxy@master ~]$ expr match “hello linux” "he" <==计算两个字符串从头匹配上的字符个数
2
2、echo命令
echo命令用于输出显示一行数据。
[hyxy@master ~]$ name=kitty
[hyxy@master ~]$ echo $name
kitty
[hyxy@master ~]$ echo this is a test
this is a test
可以使用-e ,让转义字符串生效
[hyxy@master ~]$ echo "hello\nworld"
hello\nworld
[hyxy@master ~]$ echo -e "hello\nworld" <== \n 表示换行
hello
world
[hyxy@master ~]$ echo -e "hello\nworld\c" <== \c 表示不换行
hello
world[hyxy@master ~]$
3、printf命令
与echo命令功能相同,用来输出显示数据。功能更强大,可以格式化字符串,指定字符串的宽度,左右对齐方式等等。默认情况下不换行,可以手动添加\n
语法: printf format [arguments……...]
说明: format: 格式控制字符串
arguments: 参数值列表
格式控制字符 | 表示含义 | 转义字符 | 表示含义 | |
---|---|---|---|---|
%s |
字符串 |
\a | 警告字符,通常为ASCII的BEL字符 | |
%f |
对应位置必须是浮点数。否则报错 |
\b | 后退 | |
%c |
ASCII字符,即显示对应参数的第一个字符 |
\f | 换页 | |
%d,%i |
十进制整数 |
\n | 换行 | |
%o |
八进制值 |
\r | 回车 | |
%u |
不带正负号的十进制值 |
\t | 水平制表符 | |