shell使用echo打印输出及printf格式化输出

来源:互联网 发布:防arp攻击软件 编辑:程序博客网 时间:2024/05/17 07:58

shell 打印输出
shell主要有两种输出,echo,printf,格式化输出常常使用printf

1.echo
echo是很常用的打印输出命令:
如:

echoecho ' 'echo 'hello'echo "hello"

值得注意的是单引号(’)与双引号(“)略有区别
单引号直接输出后面的字符串,而双引号可以引入变量
例如:

[root@mytest ~]# str='string'[root@mytest ~]# echo 'str'str[root@mytest ~]# echo '$str'$str[root@mytest ~]# echo "$str"string

echo也可以用分号直接衔接两个字符串:
如:

[root@mytest ~]# echo 'this is ',$strthis is ,string

有些特殊情况下,既要输出$符号,又需要输出变量,则需要转移字符\

[root@mytest ~]# echo "this is \$str is $str"this is $str is string

另外:
echo很特殊的一个作用是可以彩色输出:
-e参数

2.printf
printf与c语言的基本一致
例如:

[root@mytest ~]# printf 'hello\n'hello

printf另外一个很重要的特点是,可以格式化输出,使显示结果相对工整
例如:

[root@mytest ~]# printf "ID: %-5s  NAME: %-20s  Avage: %4.2f\n" 1  tom 74.23333;printf "ID: %-5s  NAME: %-20s  Avage: %4.2f\n" 5  jack 81.66666;printf "ID: %-5s  NAME: %-20s  Avage: %4.2f\n" 3  stve 78.50000ID: 1      NAME: tom                   Avage: 74.23ID: 5      NAME: jack                  Avage: 81.67ID: 3      NAME: stve                  Avage: 78.50
0 0
原创粉丝点击