Forループは2回実行されます。

Forループは2回実行されます。

だから私は初めてbashスクリプトに触れましたが、私は次のようなbash操作をしたいと思います。

投稿タイムスタンプを作成します。 (varまたはファイルとして)

Feeds.txt というファイルから行を読み込みます。

文字列全体で、数値文字列を2つの変数$ feedNumと$wholeStringに分割します。

次に、catコマンドを実行して$wholeStringという名前の新しいファイルを作成または追加し、timestamp.txtの内容をファイルに追加します。

最後に、wgetコマンドを実行して$ feedNumをURL文字列に挿入し、以前に生成された$wholeStringファイルにwget応答を出力します。

これが私が持っているものです。

Feeds.txtは次のようになります(最終的には長くなります)。

8147_feed_name.xml
19176_nextfeed_name.xml

私がまとめたスクリプトは次のようになりました。

#Changes the directory to the correct location
cd /home/scripts
# Inserts the proper timestamp in the file , postdating for one hour.
date -d '1 hour ago' "+%m/%d/%Y %H:%M:%S" >/home/scripts/timestamp.txt

#Loop Logic
for feedNum in `cat feeds.txt |cut -d _ -f 1`;do
   for  wholeString in `cat feeds.txt`; do
    cat /home/scripts/timestamp.txt >>/home/scripts/tmp/$wholeString ;
    wget https\://some.url.com/reports/uptimes/${feedNum}.xml?\&api_key=KEYKEYKEYKEY\&location=all\&start_date=recent_hour -O ->>/home/scripts/tmp/$wholeString;
done
done

私の問題は4回実行されることです。したがって、catとwgetを削除し、次のように単純なechoに置き換えると、

#Changes the directory to the correct location
cd /home/scripts
# Inserts the proper timestamp in the file , postdating for one hour.
date -d '1 hour ago' "+%m/%d/%Y %H:%M:%S" >/home/scripts/timestamp.txt

#Loop Logic
for feedNum in `cat feeds.txt |cut -d _ -f 1`;do
   for  wholeString in `cat feeds.txt`; do
    echo $feedNum $wholeString
done
done

上の行と下の行が正しいこのような出力を取得します。中央の2つが混ざっています。

8147 8147_feed_name.xml
8147 19176_nextfeed_name.xml
19176 8147_feed_name.xml
19176 19176_nextfeed_name.xml

なぜこれが起こるのか理解していますが、解決策はわかりません。

ベストアンサー1

これにより、文字列分割の問題が解決されます(いつものように、ファイル名のスペースに注意してください)。

#Changes the directory to the correct location
cd /home/scripts
# Inserts the proper timestamp in the file , postdating for one hour.
date -d '1 hour ago' "+%m/%d/%Y %H:%M:%S" >/home/scripts/timestamp.txt

#Loop Logic
while IFS=_ read feedNum xmlFile; do
  echo "$feedNum $xmlFile"
done < feeds.txt

wgetここで呼び出しを収集するのは簡単です。

おすすめ記事