Shell_3

echo命令

1.显示普通字符串:

echo "It is a test"

这里的双引号完全可以省略,以下命令与上面实例效果一致:

echo It is a test

 

2.显示转义字符

echo "\"It is a test\""

结果将是:

"It is a test"

同样,双引号也可以省略

 

3.显示变量

read 命令从标准输入中读取一行,并把输入行的每个字段的值指定给 shell 变量

#!/bin/sh
read name 
echo "$name It is a test"

以上代码保存为 test.sh,name 接收标准输入的变量,结果将是:

[root@www ~]# sh test.sh
OK                     #标准输入
OK It is a test        #输出

 

4.显示换行

echo -e "OK! \n" # -e 开启转义
echo "It is a test"

输出结果:

OK!

It is a test

 

5.显示不换行

#!/bin/sh
echo -e "OK! \c" # -e 开启转义 \c 不换行
echo "It is a test"

输出结果:

OK! It is a test

 

6.显示结果定向至文件

echo "It is a test" > myfile

 

7.原样输出字符串,不进行转义或取变量(用单引号)

echo '$name\"'

输出结果:

$name\"

 

8.显示命令执行结果

echo `date`

注意: 这里使用的是反引号 `, 而不是单引号 '

结果将显示当前日期

Thu Jul 24 10:08:46 CST 2014

 

Printf命令

默认的printf不会像echo一样自动添加换行符,需要手动添加\n

printf  format-string  [arguments...]

format-string:格式控制字符串

arguments:参数列表

%s:字符串,%c:输出一个字符,%d:整型输出,%f:输出实数

%-10s:宽度为10个字符,"-"表示左对齐,没有则表示右对齐

%-4.2f:格式化为小数,其中 .2 表示保留两位小数

转义序列:

 

test命令:

数值测试:

eg:

num1=100
num2=100
if test $[num1] -eq $[num2]
then
    echo '两个数相等!'
else
    echo '两个数不相等!'
fi   #fi相当于end if
→两个数相等!

a=5
b=6

result=$[a+b] # 注意等号两边不能有空格
echo "result 为: $result"
→result 为:11

 

  字符串测试:

 

文件测试:

 

posted @ 2023-05-16 14:55  LhTian21  阅读(22)  评论(0)    收藏  举报