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

时间:2022-02-18 09:09:39

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

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

echo
echo ' '
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 ',$str
this 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.50000
ID: 1 NAME: tom Avage: 74.23
ID: 5 NAME: jack Avage: 81.67
ID: 3 NAME: stve Avage: 78.50