我在 CentOS 的 init.d 脚本中看到了一个有趣的“读取”循环,基本上可以归结为这种结构:
cat "somefile" | while read var1 var2; do
# do something with vars 1 and 2
done 3<&1
我实验性地取消了“3<&1”重定向,执行或行为没有任何改变......最终重定向“3<&1”实现了什么,为什么它专门在循环结束时完成?
下面是完整的初始化脚本,它用于 Gazzang 的 zNcrypt 服务,用于处理加密文件系统的密钥管理。我感兴趣的部分发生在“开始”和“停止”案例的末尾。
#! /bin/sh
#
# zncrypt This script mount and umount all zncrypt directories
#
# chkconfig: - 64 36
# description: zNcrypt start script.
. /etc/rc.d/init.d/functions
if [ -r /usr/lib/zncrypt/zncrypt.functions ]; then
. /usr/lib/zncrypt/zncrypt.functions
else
echo "/usr/lib/zncrypt/zncrypt.functions: File does not exist."
exit 0
fi
ZNCRYPT_LOG_DIR="/var/log/zncrypt"
ZNCRYPT_LOG_ACCESS_FILE=$ZNCRYPT_LOG_DIR"/access.log"
# create zncrypt log directory
mkdir -p "$ZNCRYPT_LOG_DIR"
# create access log file for the kernel module
touch "$ZNCRYPT_LOG_ACCESS_FILE"
case "$1" in
start)
echo "Starting zNcrypt directories"
egrep -v "^[[:space:]]*(#|$)" "$ZTABFILE" | while read mnt src type opts; do
if ! df "$mnt" | grep "$mnt$" >/dev/null; then
action $" * Mounting $src ... " do_mount "$src" "$mnt" "$type" "$opts" < /dev/tty
fi
done 3<&1
;;
stop)
echo "Stopping zNcrypt directories"
egrep -v "^[[:space:]]*(#|$)" "$ZTABFILE" | while read mnt src type opts; do
if df "$mnt" | grep "$mnt$" >/dev/null; then
action $" * Umounting $src ... " do_umount "$mnt"
fi
done 3<&1
if /sbin/lsmod | grep ^zncryptfs &>/dev/null; then
action $" * Unloading module ... " /sbin/rmmod zncryptfs 2>/dev/null && rm /dev/zncrypt 2>/dev/null
fi
;;
status)
show_status
;;
restart)
/bin/bash $0 stop
sleep 1
/bin/bash $0 start
;;
reload|force-reload)
;;
force-start)
;;
*)
echo "Usage: `basename $0` {start|stop|status|restart}"
exit 1
;;
esac