スクリプトが突然別のディレクトリの代わりにシステムファイルを移動し始めます。

スクリプトが突然別のディレクトリの代わりにシステムファイルを移動し始めます。

以下のスクリプトを使用して、ソースディレクトリからターゲット1ディレクトリにファイルを移動し、ファイルをターゲット2ディレクトリにコピーします。時には/うまくいきますが、時には突然システムファイル全体をターゲットhomeに移動し始めます。ディレクトリが表示されると、システムシステム全体が破損し、修復を実行する必要があります。それで、なぜこれが起こるのか、なぜこれが起こるのか、そして何がそれを引き起こすのかわかりません。etcusr

#!/bin/bash -i
#
alias brc='source ~/.bashrc'
mydir='My-Dir1*'
min_age=5
cdate=$(date +%F)
echo -n "Enter ID: "; read u; echo $u
dstdir1="$(find  /home/myuser/Documents/dstdir1/customers/ -maxdepth 1 -name "*${u}*" -type d)/Transaction_$cdate"
dstdir2="$(find  /home/myuser/Documents/dstdir2/customers/ -maxdepth 1 -name "*${u}*" -type d)/Transaction_$cdate"
mkdir -p $dstdir2
mkdir -p $dstdir1
dir_list=$(find "/home/myuser/Documents/customers/$u/" -type d -iname "$mydir" | grep -iv Recycle.Bin)
echo $dir_list
if [ -z "$dir_list" ]; then
    echo "Error: could not find any directories matching pattern $mydir" >&2
    exit 1
fi
source ~/.bashrc
cwd=$PWD
echo "SELECT THE SOURCE DIRECTORY"

onlyonce=0

select dir in $dir_list; do
    srcdir="/home/myuser/Documents/customers/$u"
    echo "Files will be moved from:"
    echo "$srcdir to"
    echo "$dstdir1 then copied to"
    echo "$dstdir2"
    read -p 'continue (y/n)? ' -r answer
    [ "$answer" = "y" ] || exit 0

    echo "Moving then coping files older than $min_age minutes."
    while :; do
        echo 'setting source file and directory permissions...'
        find "$srcdir" -type d ! -perm 0775 -exec chmod 0775 '{}' \;
        find "$srcdir" -type f ! -perm 0664 -print0 | xargs -0 -r -- chmod 0664
        cd "$srcdir"
        echo 'Moving files...'
        rsync_extra_opts='-ptOW --info=progress2 --no-super --remove-source-files'
        find . -type f -mmin +$min_age -print0 | rsync -0 --files-from=- $rsync_extra_opts ./ "$dstdir1/"
        if [ $? -ne 0 ]; then
            echo 'correcting destination directory permissions...'
            find "$dstdir1" -type d ! -perm 0775 -exec chmod -c 0775 '{}' \;
        fi
        cd "$dstdir1"
        echo 'Coping files...'
        rsync_extra_opts='-ptOW --info=progress2 --no-super'
        find . -type f -mmin +$min_age -print0 | rsync -0 --files-from=- $rsync_extra_opts ./ "$dstdir2/"
        if [ $? -ne 0 ]; then
            echo 'correcting destination directory permissions...'
            find "$dstdir2" -type d ! -perm 0775 -exec chmod -c 0775 '{}' \;
        fi

        cd "$cwd"
        df -h "$srcdir" "$dstdir1" "$dstdir2"
        echo 'sleeping 5 minutes...'
        sleep 5m
        echo ""
    done
    break
done
cd "$cwd"

ベストアンサー1

/スクリプトが実行中で保護されていないスクリプトがあるcd "$srcdir"時点で失敗するようです。

いくつかのアドバイス

  • ステートメントを使用するprintfか、set -x変数にどの値が含まれているかを確認してください。
  • rsync --dry-runテストおよびその他の非破壊作業中に使用
  • 保護cd "$srcdir"cd "$srcdir" || continue、またはif cd "$srcdir"; then ...)、または[[ -d "$srcdir" ]] || continue
  • より良い方法は、どこでもディレクトリを変更せずにcd渡すことです。rsync

おすすめ記事