博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Shell的格式化输出
阅读量:2492 次
发布时间:2019-05-11

本文共 2159 字,大约阅读时间需要 7 分钟。

1、使用echo进行格式化输出

  • 显示转义字符
[root@yanta ~]# echo "\"This is a test\"""This is a test"
  • 读取变量并显示

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

#!/bin/bash# Name: /home/yanta/read_echo.sh# Author: Yanta# Dsc: This is to test reading input argumentsUsage(){    echo "USAGE: /bin/bash /home/yanta/read_echo.sh"    echo "USAGE: This script is to test reading input arguments"}Read(){    echo -ne "Please input your name: "    read name    echo "Your name is %name"}main(){    [ $# -ne 0 ] && {        Usage        exit -1    }    Read}main $*

输出结果是:

[root@yanta yanta]# ./read_echo.shPlease input your name: yantaYour name is %name
  • 显示换行和不换行

echo 的 -e 参数开启转义;\n 换行 \c 不换行

[root@yanta yanta]# echo "Hello"Hello[root@yanta yanta]# echo -e  "Hello"Hello[root@yanta yanta]# echo -n  "Hello"Hello[root@yanta yanta]# echo -e "Hello \n" Hello [root@yanta yanta]# echo  "Hello \n"Hello \n[root@yanta yanta]# echo  "Hello \c"Hello \c[root@yanta yanta]# echo  -e "Hello \c"Hello [root@yanta yanta]#

2、使用printf进行格式化输出

  • 语法

printf 命令模仿 C 程序库(library)里的 printf() 程序。

标准所定义,因此使用printf的脚本比使用echo移植性好。
printf 使用引用文本或空格分隔的参数,外面可以在printf中使用格式化字符串,还可以制定字符串的宽度、左右对齐方式等。
默认printf不会像 echo 自动添加换行符,我们可以手动添加 \n。

printf 命令的语法:

printf format-string [arguments…]

参数说明:

format-string: 为格式控制字符串

arguments: 为参数列表。

  • 转义序列
    这里写图片描述
    Note: 转义序列只在格式字符串中会被特别对待,也就是说,出现在参数字符串里的专利序列不会被解释:
[root@yanta yanta]# printf "%s\n" "abc\ndef"abc\ndef
  • 格式化指示符
    这里写图片描述
  • 精度

    这里写图片描述

  • 格式标志

    这里写图片描述

实例:

#!/bin/bash############ Name: printf.sh# Author: Yanta# Dsc: Test printf format output###########Usage(){    echo "USAGE: /bin/bash /home/yanta/printf.sh"    echo "USAGE: This script is to test printf format output"}Print(){    for i in sshd ntpd firewalld    do        res=`systemctl status $i | grep -e running | wc -l`        [ $res -ne 0 ] && {            stat=`echo -e "\033[1;5;32mRunning\033[0m"`        } || {            stat=`echo -e "\033[1;5;31mFailed\033[0m"`        }        printf "[%-5s] \t%-s \t[%5s]\n" "$i" "<-->" "$stat"    done}main(){    [ $# -ne 0 ] && {        Usage        exit -1    }    Print}main $*

输出:

[root@yanta yanta]# ./printf.sh [sshd ]       <-->      [Running][ntpd ]       <-->      [Running][firewalld]   <-->      [Failed]
你可能感兴趣的文章
django搭建一个小型的服务器运维网站-拿来即用的bootstrap模板
查看>>
redis事务
查看>>
Java_基础语法之dowhile语句
查看>>
HDU 2175 汉诺塔IX
查看>>
PAT 甲级 1021 Deepest Root
查看>>
查找代码错误.java
查看>>
vc获取特殊路径(SpecialFolder)
查看>>
单例模式
查看>>
int(3)和int(11)区别
查看>>
201521123061 《Java程序设计》第十一周学习总结
查看>>
代码小思考
查看>>
Unity中的销毁方法
查看>>
ceph删除pool提示(you must first set the mon_allow_pool_delete config option to true)解决办法...
查看>>
2016-7-15(1)使用gulp构建一个项目
查看>>
CSS 设计指南(第3版) 初读笔记
查看>>
markdown学习/mou
查看>>
CentOS 搭建 LAMP服务器
查看>>
记录在Spring-Boot中使用Fegin调用RESTfull的PATCH方法设置
查看>>
Php和httpd.conf的配置
查看>>
正则10-18
查看>>