我不喜欢我所看到的代码的方式,因此我将所有主要“块”压缩为函数。 (如果存在错误,这也会阻止代码运行。)我不知道这是否是不好的做法。这是代码(关于第一行:bash-4.3
安装在/usr/local/bin/bash
. 中):
#!/usr/local/bin/bash
cat /dev/null > out.txt
resetcolor() {
echo -ne "\e[0m"
}
color() {
resetcolor
if [ $# -eq 1 ]
then
echo -ne "\033[38;5;${1}m"
elif [ $2 == "b" ]
then
echo -ne "\033[1;38;5;${1}m"
fi
}
prob() {
x=$(echo "scale=4;($1/$c)" | bc)
y=$(echo "scale=2;$x*100" | bc)
if [[ ${y%??} == *".00"* ]] ; then echo "${y%?????}%"
elif [[ ${y#????} == "000" ]] ; then echo "${y%????}%"
elif [[ ${y#???} == "3300" ]] ; then echo "${y%?????}.33%"
elif [[ ${y#???} == "6600" ]] ; then echo "${y%?????}.67%"
else echo "${y%??}%"
fi
}
readmessage() {
if [ $# -eq 1 ]
then
c=$1
echo "Flipping coins..."
else
echo "Enter number of coins to flip..."
read c
echo "Flipping coins..."
fi
}
flip() {
< /dev/urandom LC_CTYPE=C gtr -dc HT | head -c $c | while read -n 1 ccoin
do
echo -n "$ccoin"
echo "$ccoin" >> out.txt
done
echo -e "\n"
}
stats() {
if (($c<10))
then
exit 1
else
co=$( < out.txt )
color 035
echo "Heads:"
h=`grep -o "H" <<<"$co" | wc -l`
color 047 b
echo $h
resetcolor
color 027
echo "Tails:"
color 045 b
t=`grep -o "T" <<<"$co" | wc -l`
echo $t
color 255 b
echo " "
echo "Experimental probability"
echo "Heads:"
prob $h
echo "Tails:"
prob $t
fi
}
###
readmessage $1
flip
stats
###
答案1
绝对是不是这是一个不好的做法。使用函数是将代码划分为块的好方法之一。这样就可以很容易地:
- 查看启用了哪些代码部分
- 禁用部分代码
- 查看代码的哪些部分在做什么,因为它们被标记并通过函数与代码的其他部分清楚地分开