程序包: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