检查配置文件中的键值对,如果未设置某些值,则提示消息



我想读取配置文件并检查所有键值对,如果未设置某些值,则提示用户未设置这些特定的键值。

我正在尝试通过在配置文件中获取然后根据需要检查密钥来实现这一目标:-

 if [ ! -r "${file}" ]; then
    echo "Lfile is not readable kindly verify"
  elif [ ! -r "${file1}"]; then
    echo "file1 is not readable kindly verifry"
  elif [ -z $key ];then
    echo "KEY_ is not set"
 elif.....
   .....
fi 

但是在这种情况下,我遇到的问题是,它将列出所有键值 paris 并在脚本中进一步移动,但我希望它中止以防某些值未设置并在终端上提示该值

如果我在两者之间使用退出,例如:-

if [ ! -r "${file}" ]; then
    echo "Lfile is not readable kindly verify"
    exit
  elif [ ! -r "${file1}"]; then
   echo "file1 is not readable kindly verify"
   exit

它一次只会提示一个未定义的值。

所以我的问题是如何使我的脚本检查整个键值对并列出所有未设置的键。

你可以像这样编写脚本:

if [ ! -r "${file}" ]; then
    echo "Lfile is not readable kindly verify"
    exit 1
elif [ ! -r "${file1}"]; then
   echo "file1 is not readable kindly verify"
   exit 1
fi
# list of all keys you want to check for
allKeys=("key1" "key2" "key3" "key4")
missing=()
for k in ${allKeys[@]}; do
    [[ -z "${!k}" ]] && missing+=($k)
done
if [[ ${#missing[@]} -gt 0 ]]; then
    printf "Missing keys are: %st" "${missing[@]}"
    echo ""
    exit 1
fi

你可以使用数组

arr=()
key1="hi"
key2="bye"
arr+=($key1)
arr+=($key2)
echo ${arr[@]}

最新更新