1

我正在尝试将特定目录上的内容同步到不同的服务器并创建脚本以使其自动化。我的脚本将检查目录的内容是否有文件或文件夹,然后使用 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 脚本的了解没什么好大惊小怪的,但我正在努力让它发挥作用。

4

3 回答 3

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

我发现这是一个很好的可重用代码。

于 2013-06-03T17:22:43.500 回答
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
于 2013-06-03T17:14:31.160 回答
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
于 2013-06-03T17:15:26.990 回答