【Shell】脚本文件实现数据的输出(纯干货)
一、echo用法:
echo使用说明:
echo命令支持-e选项,使用该选项可以让echo命令识别\后面的转义符号含义,常见转义符号如表1-1所示。其中\033或\e后面可以跟终端编码,终端编码可以用于定义终端的字体颜色、背景颜色、定位光标等。
①使用echo命令编写一个更有趣的脚本文件菜单!
#!/bin/bash
#version:1.0
#这个脚本仅演示菜单输出,没有具体的功能实现
echo "这是一个打印菜单的例子"
echo "1.查看网卡信息"
echo "2.查看内存信息"
echo "3.查看磁盘信息
4.查看CPU信息
5.查看账户信息"
#!/bin/bash
#Version:2.0
clear
echo -e "\033[42m---------------------------------\033[0m"
echo -e "\e[2;10H这里是菜单\t\t#"
echo -e "#\e[32m 1.查看网卡信息\e[0m #"
echo -e "#\e[33m 2.查看内存信息\e[0m #"
echo -e "#\e[34m 3.查看磁盘信息\e[0m #"
echo -e "#\e[35m 4.查看CPU信息\e[0m #"
echo -e "#\e[36m 5.查看账户信息\e[0m #"
echo -e "\033[42m---------------------------------\033[0m"
echo
②彩色打印字体
annie.wu@RMSH06:~/work$ echo -e "\033[1mOK" #加粗显示OK后没关闭属性
annie.wu@RMSH06:~/work$ echo -e "\e[1mOK\e[0m" #使用\e和\033的效果相同
annie.wu@RMSH06:~/work$ echo -e "\e[4mOK\e[0m" #加下划线后输出OK
annie.wu@RMSH06:~/work$ echo -e "\e[5mOK\e[0m" #闪烁显示OK
annie.wu@RMSH06:~/work$ echo -e "\e[30mOK\e[0m" #黑色显示OK
annie.wu@RMSH06:~/work$ echo -e "\e[31mOK\e[0m" #红色显示OK
annie.wu@RMSH06:~/work$ echo -e "\e[32mOK\e[0m" #绿色显示OK
annie.wu@RMSH06:~/work$ echo -e "\e[33mOK\e[0m" #棕色显示OK
annie.wu@RMSH06:~/work$ echo -e "\e[34mOK\e[0m" #蓝色显示OK
annie.wu@RMSH06:~/work$ echo -e "\e[35mOK\e[0m" #紫色显示OK
annie.wu@RMSH06:~/work$ echo -e "\e[36mOK\e[0m" #蓝绿色显示OK
annie.wu@RMSH06:~/work$ echo -e "\e[37mOK\e[0m" #亮灰色显示OK
annie.wu@RMSH06:~/work$ echo -e "\e[1;33mOK\e[0m" #亮黄色显示OK
annie.wu@RMSH06:~/work$ echo -e "\e[42mOK\e[0m" #绿色背景显示OK
annie.wu@RMSH06:~/work$ echo -e "\e[44mOK\e[0m" #蓝色背景显示OK
annie.wu@RMSH06:~/work$ echo -e "\e[32;44mOK\e[0m" #绿色字体,蓝色背景显示OK
③实际应用Log区分打印:
echo -e "\e[32m[ info `date "+%Y-%m-%d %H:%M:%S"`]\e[0m"
echo -e "\e[31m[ error `date "+%Y-%m-%d %H:%M:%S"`]\e[0m"
echo -e "\e[33m[ warning `date "+%Y-%m-%d %H:%M:%S"`]\e[0m"
二、printf用法:
annie.wu@RMSH06:~/work$ printf "%d\n" 12
12
annie.wu@RMSH06:~/work$ printf "%d\n" abc
-bash: printf: abc: invalid number
0
annie.wu@RMSH06:~/work$ printf "%5d\n" 12
12
annie.wu@RMSH06:~/work$ printf "%-5d\n" 12
12
annie.wu@RMSH06:~/work$ printf "|%-10d|\n" 12 #右对齐输出12,占用10位宽度
|12 |
annie.wu@RMSH06:~/work$ printf "|%10d|\n" 12 #左对齐输出12,占用10位宽度
| 12|
annie.wu@RMSH06:~/work$ printf "%o\n" 10 #显示10的八进制值,八进制12转换为十进制正好是10
12
annie.wu@RMSH06:~/work$ printf "%x\n" 10 显示10的十六进制值
a
annie.wu@RMSH06:~/work$ printf "%d\n" 0x11
17
annie.wu@RMSH06:~/work$ printf "%d\n" 011
9
annie.wu@RMSH06:~/work$ printf "%u\n" 92347436534856442
92347436534856442
annie.wu@RMSH06:~/work$ printf "%f\n" 3.55 #打印小数
3.550000
annie.wu@RMSH06:~/work$ printf "%.3f\n" 3.55 #打印小数,小数点后保留3位
3.550
annie.wu@RMSH06:~/work$ printf "|%8.3f|\n" 3.55 #右对齐,占用8位宽度
| 3.550|
annie.wu@RMSH06:~/work$ printf "|%-8.3f|\n" 3.55 #左对齐,占用8位宽度
|3.550 |
annie.wu@RMSH06:~/work$ printf "%s\n" "hello" #打印字符串
hello
annie.wu@RMSH06:~/work$ printf "|%10s|\n" "hello" #右对齐,占用10位宽度
| hello|
annie.wu@RMSH06:~/work$ printf "|%-10s|\n" "hello" #左对齐,占用10位宽度
|hello |
annie.wu@RMSH06:~/work$ printf "%s\t%s\n" "hello" "worlf" #tab间隔打印2个字符串
hello worlf