だから私は基本的にDockerアプリケーションをすばやく実行するためのスクリプトを書いています。
私の機能の1つについて質問があります。
function prompt_user() {
echo "Enter details for docker build! If it's a new build, you can leave Host Directory and Remote Directory blank."
echo "If you've already assigned variables and are running the host you can leave the already filled vars blank if you entered them before"
echo " "
echo "Enter details:"
read -p "Image Name: " IMAGE_NAME
read -p "IP Address: " IP_ADDRESS
read -p "Port 1: " PORT_ONE
read -p "Port 2: " PORT_TWO
read -p "Container Name: " CONTAINER_NAME
read -p "Node Name: " NODE_NAME
read -p "Host Directory (Can leave this blank if you're building a new image): " HOST_DIRECTORY
read -p "Remote Directory (Can leave this blank if you're building a new image): " REMOTE_DIRECTORY
}
冗長読み取りを減らし、すべての入力を変数に割り当てる簡単な方法はありますか?
ここ確認したい場合は、スクリプト全体があります。
答え1
これが既存の関数よりどれほどきれいかはわかりませんが、forループと組み合わせた連想配列(bash v4.0以降が必要)を使用すると、時間読み取りを使用できます。
function prompt_user() {
declare -A prompt_questions
vars=(IMAGE_NAME IP_ADDRESS PORT_ONE PORT_TWO CONTAINER_NAME NODE_NAME HOST_DIRECTORY REMOTE_DIRECTORY)
prompt_questions=(
[IMAGE_NAME]='Image Name'
[IP_ADDRESS]='IP Address'
[PORT_ONE]='Port 1'
[PORT_TWO]='Port 2'
[CONTAINER_NAME]='Container Name'
[NODE_NAME]='Node Name'
[HOST_DIRECTORY]="Host Directory (Can leave this blank if you're building a new image)"
[REMOTE_DIRECTORY]="Remote Directory (Can leave this blank if you're building a new image)"
)
cat <<EOF
Enter details for docker build! If it's a new build, you can leave Host Directory and Remote Directory blank.
If you've already assigned variables and are running the host you can leave the already filled vars blank if you entered them before
Enter details:
EOF
for var in "${vars[@]}"; do
read -rp "${prompt_questions[$var]}: " "$var"
done
}
答え2
私は現在のコードがそれほど悪くないと思います。唯一繰り返されるのは、ほんのread -p
数文字にすぎません。とにかく変数名やヒントを取り除くことはできません。
(一部の人は対話的に要求するスクリプトよりもコマンドライン引数を好むかもしれませんが、これは好みの問題です。)
とにかく、変数名の二重リストを要求する@Jesse_bの連想配列があまり気に入らないと言ったので、ここに別のオプションがあります。
prompt_user() {
queries=(
IMAGE_NAME='Image Name'
IP_ADDRESS='IP Address'
PORT_ONE='Port 1'
PORT_TWO='Port 2'
CONTAINER_NAME='Container Name'
NODE_NAME='Node Name'
HOST_DIRECTORY="Host Directory (Can leave this blank if you're building a new image)"
REMOTE_DIRECTORY="Remote Directory (Can leave this blank if you're building a new image)"
)
echo "Enter details for docker build! If it's a new build, you can leave Host Directory and Remote Directory blank."
echo "If you've already assigned variables and are running the host you can leave the already filled vars blank if you entered them before"
echo " "
echo "Enter details:"
for query in "${queries[@]}"; do
read -rp "${query#*=}: " "${query%%=*}"
done
}
"${query#*=}"
最初の等号で"${query%%=*}"
文字列を効果的に分割します。query