linux - 如何要求用户输入,这应该是必需的

标签 linux bash shell

我想通过 shell 脚本要求用户输入数据库名称、数据库用户等数据。

当用户无意中按下回车键时,输入为空白。我如何使输入成为必需的?如果输入为空,脚本会再次询问该问题?

我当前的脚本,但可能无法按我的预期运行。

#!/bin/bash
# Clear terminal first
clear

echo -n "Your Database Name : "
read dbname
if [ "$dbname" = "" ]; then
   echo "ANSWER CANNOT BE BLANK!"
   echo -n "Your Database Name : "
   read dbname
else
... another code here

但这并不排除用户没有意外(甚至可能是故意)按下回车键的可能性——我必须做出多少 if else 条件?

最佳答案

如果输入不为空,您可以使用无限循环和break:

while true; do
  echo -n "Your Database Name: "
  read dbname
  if [[ "$dbname"  != "" ]]
  then
    echo "dbname = $dbname"
    break
  fi
done

关于linux - 如何要求用户输入,这应该是必需的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39576390/

相关文章:

linux - 挂载远程文件系统 - 挂载后和卸载前脚本 (linux)

java - 如何为 .jar 命令行脚本创建别名?

python - 如何在 Python 中录制系统音频? (Linux)

java - 在 Linux 上运行 jar 文件时出现此错误 - 线程 "main"java.lang.NoClassDefFoundError : org/apache/log4j/Logger 中的异常

python - USB串口数据发送乱码

linux - 使用 --color=always 选项时 grep 结果不同

bash - 如何在 bash 中从第 x 行读取文件到文件末尾

linux - dd命令调整文件系统

bash - 递归地将文件放入Unix中的回收站

shell - 如何在shell脚本中双管道后执行多个命令