2017-08-15 8 views
0

あるディレクトリ内のファイルが別のディレクトリ内のファイルよりも最近変更された場合、シェルスクリプトでコマンドを実行します。シェルスクリプト:あるディレクトリ内のファイルが別のディレクトリ内のファイルより新しいかどうか確認してください。

BashFAQ #3で説明した再利用可能な機能の中に、ここで分解として、私はこの

if [ dir1/* <have been modified more recently than> dir2/* ]; then 
    echo 'We need to do some stuff!' 
fi 
+1

参照[BashFAQ#3](http://mywiki.wooledge.org/BashFAQ/003)。それぞれのディレクトリで最新のファイルを探し、それらを個別に比較する必要があります。 FAQはそれらすべてのことをする方法を教えてくれます。 –

+1

'dir1'の* any *ファイルが' dir2'の* any *ファイルより最近に変更された場合?あるいは、彼らは同じ構造を持ち、ペアを比較したいのですか? –

+0

@BenjaminW。、...私は確かに前者を暗示して擬似コードを読んだ。 –

答えて

0

ような何かをしたいと思います:

newestFile() { 
    local latest file 
    for file; do 
    [[ $file && $file -nt $latest ]] || latest=$file 
    done 
} 

directoryHasNewerFilesThan() { 
    [[ "$(newestFile "$1"/*)" -nt "$(newestFile "$2" "$2"/*)" ]] 
} 

if directoryHasNewerFilesThan dir1 dir2; then 
    echo "We need to do something!" 
else 
    echo "All is well" 
fi 

あなたはファイルとしてディレクトリ自体をカウントしたい場合は、あなたが行うことができますそれも。 "$(newestFile "$1"/*)""$(newestFile "$1" "$1"/*)"と置き換え、同様にnewestFile$2と呼びます。

0

使用/ binに/ LS

#!/usr/bin/ksh 

dir1=$1 
dir2=$2 

#get modified time of directories 
integer dir1latest=$(ls -ltd --time-style=+"%s" ${dir1} | head -n 2 | tail -n 1 | awk '{print $6}') 
integer dir2latest=$(ls -ltd --time-style=+"%s" ${dir2} | head -n 2 | tail -n 1 | awk '{print $6}') 

#get modified time of the latest file in the directories 
integer dir1latestfile=$(ls -lt --time-style=+"%s" ${dir1} | head -n 2 | tail -n 1 | awk '{print $6}') 
integer dir2latestfile=$(ls -lt --time-style=+"%s" ${dir2} | head -n 2 | tail -n 1 | awk '{print $6}') 

#sort the times numerically and get the highest time 
val=$(/bin/echo -e "${dir1latest}\n${dir2latest}\n${dir1latestfile}\n${dir2latestfile}" | sort -n | tail -n 1) 

#check to which file the highest time belongs to 
case $val in 
    @(${dir1latest}|${dir1latestfile})) echo $dir1 is latest ;; 
    @(${dir2latest}|${dir2latestfile})) echo $dir2 is latest ;; 
esac