我写了一个脚本来备份到/mount/data/
中的挂载磁盘,我不想在复制其他文件夹的同时复制该文件夹,我也不想复制proc
,sys
。
for dir in `ls /`; do
if [ $dir != "mount" -o $dir != "proc" -o $dir != "sys" ]; then
sh /home/bin/safecopy $dir
fi
done
但是这个条件被忽略了
$dir != "mount" -o $dir != "proc" -o $dir != "sys"
而
safecopy
试图复制mount
,proc
和sys
。为什么?但当我这样做的时候
for dir in `ls /`; do
if [ $dir != "mount" ]; then
if [ $dir != "proc" ]; then
if [ $dir != "sys" ]; then
sh /home/bin/safecopy $dir
fi
fi
fi
done
它起作用了!
最佳答案
假设需要在bash以外的shell上运行,一个好的方法是使用case
,因为它支持模式匹配(与[
不同):
for dir in /*/; do
case $dir in
/mount/|/proc/|/sys/)
:
;;
*)
/home/bin/safecopy "$dir"
;;
esac
done
特别是对于bash,可以使用:
shopt -s extglob
for dir in /!(mount|proc|sys)/; do
/home/bin/safecopy "$dir"
done
不要在脚本中迭代,甚至不要使用
ls
。不要使用单词分割命令替换输出,引用它们。
不要使用反勾,使用
"$(cmd)"
。在使用经典的
-a
命令(-o
)时,不要使用test
或[
。使用[测试][测试]…使用引号!他们在几个重要的地方失踪了。
如果不需要到
safecopy
的特殊参数,则不必用“sh”调用“sh
”。将shebang添加到脚本中,并像任何其他命令一样调用它,或者如果它是一个库,则将其作为源并直接使用其函数。