xargsを使用して変数を動的に設定および変更する方法は?

xargsを使用して変数を動的に設定および変更する方法は?

docker save -o1つのコマンドでdocker-compose.yamlファイルのすべての画像に対して操作を実行しようとしています。

私ができたことは次のとおりです。

cat docker-compose.yaml | grep imageこれにより、以下が提供されます。

 image: hub.myproject.com/dev/frontend:prod_v_1_2
 image: hub.myproject.com/dev/backend:prod_v_1_2
 image: hub.myproject.com/dev/abd:v_2_3
 image: hub.myproject.com/dev/xyz:v_4_6

各イメージに対して次のコマンドを実行する必要があります。

docker save -o frontend_prod_v_1_2.tar hub.myproject.com/dev/frontend:prod_v_1_2

私が達成したことは次のとおりです。

cat docker-compose.yml | grep image | cut -d ':' -f 2,3これは作る:

 hub.myproject.com/dev/frontend:prod_v_1_2
 hub.myproject.com/dev/backend:prod_v_1_2
 hub.myproject.com/dev/abd:v_2_3
 hub.myproject.com/dev/xyz:v_4_6

私もできます:

cat docker-compose.yml | grep image | cut -d ':' -f 2,3 | cut -d '/' -f3 | cut -d ':' -f1,2

これは作る:

 frontend:prod_v_1_2
 backend:prod_v_1_2
 abd:v_2_3
 xyz:v_4_6

それから私は何をすべきかわかりません。私はtoを使って変数に渡そうとしましたが、xargsコマンドラインでfrontend:prod_v_1_2xargsを動的に変更する方法がわかりません。frontend_prod_v_1_2.tarまた、最後には完全なイメージ名とタグが必要です。

私は似たようなものを探しています:

cat docker-compose.yml | grep image | cut -d ':' -f 2,3 | xargs -I {} docker save -o ``{} | cut -d '/' -f3 | cut -d ':' -f1,2 | xargs -I {} {}.tar`` {}

bashの魔術師はヒントを提供できますか?

ベストアンサー1

より多くのコマンドを追加すると、パイプライン方法が複雑になる可能性があります。この場合、bash対応する操作を実行するには、基本シェルの機能を使用します。出力をgrep image docker-compose.ymlループにパイプwhile..readし、それを使用して交換を実行します。

正しいシェルスクリプトでは、次のことができます。

#!/usr/bin/env bash
# '<(..)' is a bash construct i.e process substitution to run the command and make 
# its output appear as if it were from a file
# https://mywiki.wooledge.org/ProcessSubstitution

while IFS=: read -r _ image; do
    # Strip off the part up the last '/'
    iname="${image##*/}"
    # Remove ':' from the image name and append '.tar' to the string and 
    # replace spaces in the image name
    docker save -o "${iname//:/_}.tar" "${image// }"
done < <(grep image docker-compose.yml)

コマンドラインで、次のコマンドを使用してdocker saveジョブを直接実行しますxargsawk

awk '/image/ { 
       n = split($NF, arr, "/"); 
       iname = arr[n]".tar"; 
       sub(":", "_", iname); fname = $2;  
       cmd = "docker save -o " iname " " fname; 
       system(cmd);
    }' docker-compose.yml

おすすめ記事