所以我正在编写一个脚本来基本上快速运行我的 docker 应用程序,我已经让一切工作得很好,它完成了我编码它要做的所有事情。
我只是对我的一项职能有疑问:
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
我不确定这比您现有的函数干净多少,但使用关联数组(需要 bash v4.0 或更高版本)与 for 循环相结合,您可以使用一次读取。
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
为第一个等号。