{ ls -l; df; echo "Done." }
# bash: syntax error: unexpected end of file
{ ls -l; df; echo "Done."; }
# ^ ### 最后的这条命令必须以分号结尾。
假定未被初始化的变量(赋值前的变量)被“清0”。事实上,未初始化的变量值为“null”,而不是0。
#!/bin/bash
echo "uninitialized_var = $uninitialized_var"
# uninitialized_var =
# 但是 . . .
# if $BASH_VERSION ≥ 4.2; then
if [[ ! -v uninitialized_var ]]
then
uninitialized_var=0 # Initialize it to zero!
fi
混淆测试符号=和-ep。请记住,=用于比较字符变量,而-ep用来比较整数。
if [ "$a" = 273 ] # $a是整数还是字符串?
if [ "$a" -eq 273 ] # $a为整数。
# 有些情况下,即使你混用-ep和=,也不会产生错误的结果。
# 然而 . . .
a=273.0 # 不是一个整数。
if [ "$a" = 273 ]
then
echo "Comparison works."
else
echo "Comparison does not work."
fi # Comparison does not work.
# 与a=" 273"和a="0273"相同。
# 类似的, 如果对非整数值使用“-ep”的话,就会产生问题。
if [ "$a" -eq 273.0 ]
then
echo "a = $a"
fi # 产生了错误消息而退出。
# test.sh: [: 273.0: integer expression expected
#!/bin/bash
minimum_version=2
# 因为Chet Ramey经常给Bash添加一些新的特征,
# 所以你最好将$minimum_version设置为2.XX,3.XX,或是其他你认为比较合适的值。
E_BAD_VERSION=80
if [ "$BASH_VERSION" \< "$minimum_version" ]
then
echo "This script works only with Bash, version $minimum or greater."
echo "Upgrade strongly recommended."
exit $E_BAD_VERSION
fi
...
# 循环的管道问题。
# 这个例子由Anthony Richardson编写,
#+ 由Wilbert Berendsen补遗。
foundone=false
find $HOME -type f -atime +30 -size 100k |
while true
do
read f
echo "$f is over 100KB and has not been accessed in over 30 days"
echo "Consider moving the file to archives."
foundone=true
# ------------------------------------
echo "Subshell level = $BASH_SUBSHELL"
# Subshell level = 1
# 没错, 现在是在子shell中运行。
# ------------------------------------
done
# 变量foundone在这里肯定是false,
#+ 因为它是在子shell中被设置为true的。
if [ $foundone = false ]
then
echo "No files need archiving."
fi
# =====================现在,下边是正确的方法:=================
foundone=false
for f in $(find $HOME -type f -atime +30 -size 100k) # 这里没使用管道。
do
echo "$f is over 100KB and has not been accessed in over 30 days"
echo "Consider moving the file to archives."
foundone=true
done
if [ $foundone = false ]
then
echo "No files need archiving."
fi
# ==================这里是另一种方法==================
# 将脚本中读取变量的部分放到一个代码块中,
#+ 这样一来,它们就能在相同的子shell中共享了。
# 感谢,W.B。
find $HOME -type f -atime +30 -size 100k | {
foundone=false
while read f
do
echo "$f is over 100KB and has not been accessed in over 30 days"
echo "Consider moving the file to archives."
foundone=true
done
if ! $foundone
then
echo "No files need archiving."
fi
}