程序包:GNU coreutils
shell
shell的printf
數組
C語言的printf
bash
對「escape」的理解。英文直譯:逃離、逃脫。這裏表明:轉義。好比「反斜線轉義字符」,就是「backslash-escaped characters」。dom
echo
ide
●1 基本用法
測試
info coreutils 'echo invocation'spa
echo - 顯示一行文本,三個短選項,「-n」行尾不換行、「-e」啓用轉義字符、「-E」不啓用轉義字符(默認)。「-e」選項支持一些轉義字符的(展開)用法:orm
專業字符 |
釋義 |
示例 |
---|---|---|
\\ |
輸出反斜線 |
echo "\\"blog echo \\ |
\a |
一聲警報 |
echo -e '\a' echo -e "\x07" 十六進制表示 echo -e "\007" 八進制表示 echo -e "\0007" 八進制表示 |
\b |
退格 |
echo -ne "hello\b" |
\0NNN |
表示一個八進制數值 |
echo -e '\0041' echo -e '\007 等效於第二行 |
\xHH |
表示一個十六進制數值 |
echo -e '\x21' |
\e |
轉義 |
echo -e '\e[33m' |
[root@right mag]# echo -e '\041' ! [root@right mag]# echo -e '\0041' ! [root@right mag]# echo -e '\x21' ! [root@right mag]# echo -e "\0110\0145\0154\0154\0157" Hello [root@right mag]# echo -e '\0110\0145\0154\0154\0157' Hello [root@right mag]# echo -e \\0110\\0145\\0154\\0154\\0157 Hello
在程序中玩個炫的,像計數器同樣等待三秒的效果:
$ echo -ne "1\a\b";sleep 1;echo -ne "2\a\b";sleep 1;echo -ne "3\a\b";sleep 1
●2 輸出隨機數
輸出一個隨機數:
[root@right ~]# echo $RANDOM 18130
輸出一個「八進制」的隨機數(0~7):
[root@right ~]# echo $[$RANDOM%8] 5 [root@right ~]# echo $[$RANDOM%8] 2
輸出一個雙色球的紅球號(1-33):
[root@right ~]# echo $[$RANDOM%33+1] 33
*驗證隨機數獲取的隨機性
驗證腳本;經驗證10000次才能獲得較理想的結果。
#!/bin/bash # Verify that the randomness of random numbers is # not normally distributed. # The random number comes from "$RANDOM". # Generates a random number. #num="$[$RANDOM%10+1]" #echo $num # var The number of validations. var=$1 # The array is used to count the number of occurrences # of random numbers. result[0] returns the value as a # running script. # sum - The sum of the array values. result=(0 0 0 0 0 0 0 0 0 0 0) sum=0 # The occurrence of statistical random numbers. for ((i=0; i<var; i++)); do num="$[$RANDOM%10+1]" case $num in 1) let result[1]+=1 ;; 2) let result[2]+=1 ;; 3) let result[3]+=1 ;; 4) let result[4]+=1 ;; 5) let result[5]+=1 ;; 6) let result[6]+=1 ;; 7) let result[7]+=1 ;; 8) let result[8]+=1 ;; 9) let result[9]+=1 ;; 10) let result[10]+=1 ;; *) result[0]=1 echo "There was an error running the script. Error" echo -e "\a" exit ${result[0]} ;; esac done # Output array. for ((i=1; i<=10; i++)); do echo "result[$i] = ${result[i]}" let sum+=${result[i]} done echo "sum = $sum"
測試示例(接近5分鐘):
[root@right mag]# ./tes.sh 10000000 result[1] = 999048 result[2] = 999651 result[3] = 1000614 result[4] = 999725 result[5] = 1000150 result[6] = ×××00 result[7] = 1000972 result[8] = 999712 result[9] = 1000448 result[10] = 1000480 sum = 10000000
●3 輸出一個數組
字符數組輸出:
[root@right mag]# echo {a..z} a b c d e f g h i j k l m n o p q r s t u v w x y z
數字數組輸出:
[root@right mag]# echo {1..9} 1 2 3 4 5 6 7 8 9
輸出ASCII字符表(先寫個腳原本生成):
#!/bin/bash # ascii=`echo -e {000..177} | sed 's/[[:space:]]/\n/g' | grep -v 8 | grep -v 9` #echo $ascii echo "Beginning..." for i in $(echo $ascii); do echo -n "$i: " echo -e "\0$i" done