我正在尝试将特定目录上的内容rsync到另一台服务器并创建脚本以使其自动化。 我的脚本将检查该目录的内容是否包含文件或文件夹,然后使用rsync移动它们。下面,
#!/bin/bash
for i in `ls /root/tags/` ; do
if [ -f "$i" ]
then
echo "this is a file and I'll run a script if it is a file"
else
if [ -d "$i" ]
then
echo "this is a dir and I'll run a script if it is a directory"
fi
fi
done
正如你所看到的,我对shell脚本的了解不是什么值得大喊大叫的,但我正试图让它工作。
答案 0 :(得分:3)
另一种选择是
cd /root/tags
for i in * ; do
if [ -f "$i" ]; then
echo "this is a file and I'll run a script if it is a file"
elif [ -d "$i" ]; then
echo "this is a dir and I'll run a script if it is a directory"
fi
done
这与
相同path="/root/tags"
for i in "${path%/}"/* ; do
if [ -f "$i" ]; then
echo "this is a file and I'll run a script if it is a file"
elif [ -d "$i" ]; then
echo "this is a dir and I'll run a script if it is a directory"
fi
done
我发现这是一个很好的可重用代码。
答案 1 :(得分:1)
您对else if
的使用不正确,应为elif
if [ -f "$i" ]; then
echo "this is a file and I'll run a script if it is a file"
elif [ -d "$i" ]; then
echo "this is a dir and I'll run a script if it is a directory"
fi
答案 2 :(得分:0)
要确保名称中包含空格的文件不会导致问题,请使用以下内容:
find . -maxdepth 1 -print0 | while read -d "" file ; do
if [ -f "$file" ] ; then
echo "$file is a file and I'll run a script if it is a file"
elif [ -d "$file" ] ; then
echo "$file is a dir and I'll run a script if it is a directory"
fi
done