shell 在Bash中使用数组读取用户输入[已关闭]

wgx48brx  于 2023-03-09  发布在  Shell
关注(0)|答案(2)|浏览(137)

已关闭。此问题需要超过focused。当前不接受答案。
**想要改进此问题吗?**更新此问题,使其仅关注editing this post的一个问题。

3天前关闭。
Improve this question
我正在努力创建一个逻辑来问脚本用户这么多的问题,因为我在json数组。
假设它看起来像这样(它是使用jq从一个更大的json中检索到的):

[
  "key1",
  "key2",
  "key3",
  "key4",
  ...
]

我想问脚本用户一些问题,例如:key1的值是多少,key2的值是多少,等等,每个答案都应该存储在某个外部文件中,我在Mac上使用ZSH。

bnlyeluc

bnlyeluc1#

我建议迭代你想要存储的键数组,然后提示用户并在循环中动态地存储变量。下面是我如何做的一个粗略的实现:

json_array='[
  "key1",
  "key2",
  "key3",
  "key4"
]'

# `jq` idea + syntax borrowed from @Philippe
(jq -r '.[]' <<< "$json_array") | while read -r key; do
  echo -n "What is the value for $key? > "
  read -r value < /dev/tty

  # Now you have the input stored in $value, so you can do
  # whatever you want with it. If you want to store it in a
  # file, this is one simple example of to do it:
  echo "$key=$value"  >> userInput.txt
done
pcrecxhr

pcrecxhr2#

试试这个:

#!/usr/bin/ env bash

json_array='[
  "key1",
  "key2",
  "key3",
  "key4"
]'

while read -r key; do
  echo -n "What is the value for $key? > " > /dev/tty
  read -r value < /dev/tty
  echo "$key=$value"
done < <(jq -r '.[]' <<< "$json_array") > userInput.txt

相关问题