Bash - 特定のコマンドを実行できなかった配列要素を保存する

Bash - 特定のコマンドを実行できなかった配列要素を保存する
read -r -p "Enter the filenames: " -a arr

for filenames in "${arr[@]}"; do
   if [[ -e "${filenames}" ]]; then
        echo "${filenames} file exists (no override)"
   else
        cp -n ~/Documents/library/normal.py "${filenames}"
   fi
done

B.py D.py私がフォルダにあるとしましょう。

同じフォルダでこのスクリプトを実行し、名前付きファイルにA.py B.py C.py D.py(未定義の入力数)書き込むと、正常にコピーされます。
A.py C.py

については と がB.py D.pyそれぞれ表示されます。B.py file exists (no override)D.py file exists (not override)

基本配列以外の配列which did workedに要素を保存したいと思います。which didn't work${arr[@]}

arr=('A.py' 'B.py' 'C.py' 'D.py')
didworked=('A.py' 'C.py')
notworked=('B.py' 'D.py')

どうすればいいですか?提案があれば提出してください。

ベストアンサー1

その配列の正しい場所にファイル名を追加するだけです。

#!/bin/bash
files=('A.py' 'B.py' 'C.py' 'D.py')
files_err=()
files_ok=()
for f in "${files[@]}"; do
   if [[ -e "$f" ]]; then
        echo "$f file exists (no override)"
        files_err+=("$f")
   else
        if cp -n ~/Documents/library/normal.py "$f"; then
            files_ok+=("$f")
        else
            # copy failed, cp should have printed an error message
            files_err+=("$f")
        fi
   fi
done

(私はfilenamesそれをforのループ変数として使用しません。それはただのファイル名(一度)に過ぎません。)

おすすめ記事