Shell的格式化輸出

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 arguments

Usage(){
    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.sh
Please input your name: yanta
Your 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]
發佈了55 篇原創文章 · 獲贊 20 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章