我有以下情況:bash腳本來觀看一個文件夾
有已經安裝在Linux機器上的Windows文件夾。可能有多個文件夾(安裝前手) 在這個窗口安裝。我必須做一些事情(最好是一個腳本開始)觀看這些文件夾。
這些步驟如下: 觀看任何傳入文件(多個)。確保它們完全轉移。 將其移至另一個文件夾。 我沒有在Windows機器上的文件傳輸程序的任何控制。我相信這是一個安全的FTP。 所以我不能要求這個過程給我拖文件,以確保文件傳輸的完成。
我寫了一個bash腳本。我想知道這種方法的潛在缺陷。理由是, 有多個目錄像這樣運行此腳本的多張拷貝的可能性。
目前,可能有多達100個可能需要監視的目錄。
以下是腳本。我很抱歉在這裏粘貼很長的一個。請花些時間來評論它並 評論/批評它。 :-)
它需要3個參數,需要觀察的文件夾,文件必須被移動的文件夾, 和時間間隔,這在下面已經解釋。
對不起,對齊似乎存在問題。 Markdown似乎並不喜歡它。我試圖妥善組織它,但無法做到這一點。
Linux servername 2.6.9-42.ELsmp #1 SMP Wed Jul 12 23:27:17 EDT 2006 i686 i686 i386 GNU/Linux
#!/bin/bash
log_this()
{
message="$1"
now=`date "+%D-%T"`
echo $$": "$now ": " $message
}
usage()
{
cat << EOF
Usage: $0 <Directory to be watched> <Directory to transfer> <time interval>
Time interval is the amount of time after which the modification time of a
file will be monitored.
EOF
`exit 1`
}
if [ $# -lt 2 ]
then
usage
fi
WATCH_DIR=$1
APP_DIR=$2
if [ ! -d "$WATCH_DIR" ]
then
log_this "FATAL: WATCH_DIR, $WATCH_DIR does not exist. Exiting"
exit 1
fi
if [ ! -d "$APP_DIR" ]
then
log_this "APP_DIR: $APP_DIR does not exist. Exiting"
exit 1
fi
# This needs to be set after considering the rate of file transfer.
# Represents the seconds elapsed after the last modification to the file.
# If not supplied as parameter, defaults to 3.
seconds_between_mods=$3
if ! [[ "$seconds_between_mods" =~ ^[0-9]+$ ]]; then
if [ ${#seconds_between_mods} -eq 0 ]; then
log_this "No value supplied for elapse time. Defaulting to 3."
seconds_between_mods=3
else
log_this "Invalid value provided for elapse time"
exit 1
fi
fi
log_this "Start Monitor."
while true
do
ls -1 $WATCH_DIR | while read file_name
do
log_this "Start Monitoring for $file_name"
# Refer only the modification with reference to the mount folder.
# If there is a diff in time between servers, we are in trouble.
token_file=$WATCH_DIR/foo.$$
current_time=`touch $token_file && stat -c "%Y" $token_file`
rm -f $token_file 2>/dev/null
log_this "Current Time: $current_time"
last_mod_time=`stat -c "%Y" $WATCH_DIR/$file_name`
elapsed_time=`expr $current_time - $last_mod_time`
log_this "Elapsed time ==> $elapsed_time"
if [ $elapsed_time -ge $seconds_between_mods ]
then
log_this "Moving $file_name to $APP_DIR"
# In case if there is no space left on the target mount, hide the file
# in the mount itself and remove the incomplete file from APP_DIR.
mv $WATCH_DIR/$file_name $APP_DIR
if [ $? -ne 0 ]
then
log_this "FATAL: mv failed!! Hiding $file_name"
rm $APP_DIR/$file_name
mv $WATCH_DIR/$file_name $WATCH_DIR/.$file_name
log_this "Removed $APP_DIR/$file_name. Look for $WATCH_DIR/.$file_name and submit later."
fi
log_this "End Monitoring for $file_name"
else
log_this "$file_name: Transfer seems to be in progress"
fi
done
log_this "Nothing more to monitor."
echo
sleep 5
done
[用於更改監控目錄]的可能重複(http://stackoverflow.com/questions/511463/monitor-directory-for-changes) –