shell命令输出
在shell脚本中的打印输出通常会有echo和printf两种,前者会自动换行。 一、echo Shell 的 echo 指令与 PHP 的 echo 指令类似,都是用于字符串的输出。您可以使用echo实现更复杂的输出格式控制。 1.显示普通字符串: [[email?protected] ~]# echo "It is a test" It is a test [[email?protected] ~]# echo It is a test It is a test ? ?2.显示转义字符 [[email?protected] ~]# echo ""It is a test"" "It is a test" ? 3.显示变量 [[email?protected] ~]# name=”OK” [[email?protected] ~]# echo “$name It is a test” “”OK” It is a test” [[email?protected] ~]# echo $name It is a test ”OK” It is a test [[email?protected] ~]# 以下的转义字符都可在echo中使用
echo -e开启转义 -E禁止转义,默认也是不转义的 4、read read 命令从标准输入中读取一行,并把输入行的每个字段的值指定给 shell 变量。 [[email?protected] ~]# cat echo_var.sh #!/bin/sh read name echo "$name It is a test" [[email?protected] ~]# chmod 755 echo_var.sh [[email?protected] ~]# [[email?protected] ~]# ./echo_var.sh var1 var1 It is a test ? 5、显示结果定向至文件 [[email?protected] ~]# echo "It is a test" > myfile [[email?protected] ~]# [[email?protected] ~]# cat myfile It is a test ? 6、原样输出字符串,不进行转义或取变量(用单引号) [[email?protected] ~]# echo ‘$name"‘ $name" ? 7、显示命令执行结果 反引号 [[email?protected] ~]# echo `date` Mon Mar 25 22:07:23 CST 2019 ? 二、printf printf 命令用于格式化输出,是echo命令的增强版。 printf 使用引用文本或空格分隔的参数,外面可以在printf中使用格式化字符串,还可以制定字符串的宽度、左右对齐方式等。默认printf不会像 echo 自动添加换行符,我们可以手动添加换行符n。 [[email?protected] ~]# echo "Hello,Shell" Hello,Shell [[email?protected] ~]# printf "Hello,Shelln" Hello,Shell ? 格式替代符: %b 相对应的参数被视为含有要被处理的转义序列之字符串。 %c ASCII字符。显示相对应参数的第一个字符 %d,%i 十进制整数 %e,%E,%f 浮点格式 %g %e或%f转换,看哪一个较短,则删除结尾的零 %G %E或%f转换,看哪一个较短,则删除结尾的零 %o 不带正负号的八进制值 %s 字符串 %u 不带正负号的十进制值 %x 不带正负号的十六进制值,使用a至f表示10至15 %X 不带正负号的十六进制值,使用A至F表示10至15 %% 字面意义的% 三、test test 命令是Shell环境中测试条件表达式的使用工具,用于检查某个条件是否成立,它可以进行数值、字符和文件三个方面的测试。 1、数值测试
实例: [[email?protected] ~]# vi test.sh #!/bin/bash num1=100 num2=100 if test $[num1] -eq $[num2] then echo ‘两个数相等!‘ else echo ‘两个数不相等!‘ fi [[email?protected] ~]# chmod 755 test.sh [[email?protected] ~]# [[email?protected] ~]# ./test.sh 两个数相等! ? 2、字符串测试
实例: [[email?protected] ~]# vi test1.sh #!/bin/bash num1="ru1noob" num2="wiki" if test $num1 = $num2 then echo ‘两个字符串相等!‘ else echo ‘两个字符串不相等!‘ fi [[email?protected] ~]# chmod 755 test1.sh [[email?protected] ~]# [[email?protected] ~]# ./test1.sh 两个字符串不相等! 3、文件测试
[[email?protected] ~]# vi test2.sh #!/bin/bash cd /bin if test -e ./bash then echo ‘文件已存在!‘ else echo ‘文件不存在!‘ fi [[email?protected] ~]# chmod 755 test2.sh [[email?protected] ~]# [[email?protected] ~]# ./test2.sh 文件已存在! 4、条件测试 Shell还提供了与( -a )、或( -o )、非( ! )三个逻辑操作符用于将测试条件连接起来,其优先级为::“!”最高,“-a”次之,“-o”最低。 ?实例 [[email?protected] ~]# vi test3.sh #!/bin/bash cd /bin if test -e ./notFile -o -e ./bash then echo ‘有一个文件存在!‘ else echo ‘两个文件都不存在‘ fi [[email?protected] ~]# chmod 755 test3.sh [[email?protected] ~]# [[email?protected] ~]# ./test3.sh 有一个文件存在! ? end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |