检查以下脚本。运行它,然后解释它的作用。为脚本添加注释,并以更紧凑和优雅的方式重写它。
#!/bin/bash
MAX=10000
for((nr=1; nr<$MAX; nr++))
do
let "t1 = nr % 5"
if [ "$t1" -ne 3 ]
then
continue
fi
let "t2 = nr % 7"
if [ "$t2" -ne 4 ]
then
continue
fi
let "t3 = nr % 9"
if [ "$t3" -ne 5 ]
then
continue
fi
break # What happens when you comment out this line? Why?
done
echo "Number = $nr"
exit 0 |
---
解释以下脚本的作用。它实际上只是一个参数化的命令行管道。
#!/bin/bash DIRNAME=/usr/bin FILETYPE="shell script" LOGFILE=logfile file "$DIRNAME"/* | fgrep "$FILETYPE" | tee $LOGFILE | wc -l exit 0 |
---
检查并解释以下脚本。作为提示,您可以参考 find 和 stat 的列表。
#!/bin/bash
# Author: Nathan Coulter
# This code is released to the public domain.
# The author gave permission to use this code snippet in the ABS Guide.
find -maxdepth 1 -type f -printf '%f\000' | {
while read -d $'\000'; do
mv "$REPLY" "$(date -d "$(stat -c '%y' "$REPLY") " '+%Y%m%d%H%M%S'
)-$REPLY"
done
}
# Warning: Test-drive this script in a "scratch" directory.
# It will somehow affect all the files there. |
---
一位读者发来了以下代码片段。
while read LINE do echo $LINE done < `tail -f /var/log/messages` |
他希望编写一个脚本来跟踪系统日志文件的更改,/var/log/messages。不幸的是,上面的代码块挂起并且没有任何作用。为什么?修复它使其可以工作。(提示:与其重定向循环的 stdin,不如尝试管道。)
---
分析以下由 Rory Winston 贡献的 "单行脚本"(为清楚起见,此处分为两行)
export SUM=0; for f in $(find src -name "*.java");
do export SUM=$(($SUM + $(wc -l $f | awk '{ print $1 }'))); done; echo $SUM |
提示:首先,将脚本分解为小块。然后,仔细检查它对 双括号 算术、export 命令、find 命令、wc 命令和 awk 的使用。
---
分析示例 A-10,并以更简化和更符合逻辑的风格重新组织它。看看可以消除多少变量,并尝试优化脚本以加快其执行速度。
修改脚本,使其接受任何普通的 ASCII 文本文件作为其初始"生成"的输入。脚本将读取前$ROW*$COL个字符,并将元音字母的出现次数设置为"活"细胞。提示:请务必将输入文件中的空格转换为下划线字符。