Shell脚本学习指南-echo和printf运用

一、echo

1.显示转义字符

echo"\"It is a test\""         //"It is atest"  --双引号可以省略

2.显示变量

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        #输出

3.显示换行

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

输出结果:
OK!

It it a test

二、printf格式化输出

1. 基本格式

printf [format] [文本1] [文本2] ..

2.常用格式替换符

%s 字符串
%f 浮点格式
%c ASCII字符,即显示对应参数的第一个字符
%d,%i 十进制整数
%o 八进制值
%u 不带正负号的十进制值
%x 十六进制值(a-f)
%X 十六进制值(A-F)
%% 表示%本身

3. 常用转义字符

\a 警告字符,通常为ASCII的BEL字符
\b 后退
\f 换页
\n 换行
\r 回车
\t 水平制表符
\v 垂直制表符
\ 表示\本身

4. 使用示例

[keysystem@localhost ~]$ printf "%s\n" 1 2 3 4
1
2
3
4
[keysystem@localhost ~]$ printf "%f\n" 1 2 3 4
1.000000
2.000000
3.000000
4.000000
[keysystem@localhost ~]$ printf "%.2f\n" 1 2 3 4
1.00
2.00
3.00
4.00
[keysystem@localhost ~]$ printf " (%s) " 1 2 3 4;echo ""
 (1)  (2)  (3)  (4) 
[keysystem@localhost ~]$ printf "%s %s\n" 1 2 3 4
1 2
3 4
[keysystem@localhost ~]$ printf "%s %s %s\n" 1 2 3 4
1 2 3
4  
[keysystem@localhost ~]$ printf "%-10s %-10s %-4s %-4s \n" 姓名 性别 年龄 体重 苹果 男 18 60 香蕉 男 18 80       //"-"表示左对齐, "10 10 4 4" 表示占的字符位数, 不够不空格
姓名     性别     年龄 体重 
苹果     男        18   60   
香蕉     男        18   80   
[keysystem@localhost ~]$ printf "%X" 13    #10进制转16进制
D[keysystem@localhost ~]$ printf "%X\n" 13    
D
[keysystem@localhost ~]$ printf "%d" 0xB    #16进制转10进制
11
posted @ 2018-12-06 13:27  reaperhero  阅读(183)  评论(0编辑  收藏  举报