gpt4 book ai didi

linux - 如何在 bash 中读取两个输入值?

转载 作者:太空宇宙 更新时间:2023-11-04 11:54:50 24 4
gpt4 key购买 nike

我正在编写一个需要多个用户输入的 bash 脚本。在脚本执行任何操作之前,我想确保所有值都已由用户添加。

  #/bin/bash

read -p "Please enter the domain Name: " domain
read -p "Please Enter path where you want to save your result: " path
if [[ -z "$domain" && "$path"]]; then
echo "You have not entered the Domain Name"
exit 1

else
echo "Do Something Here"
fi

我已经检查了 1 个用户输入,工作正常,但是当尝试使用 2 个用户输入时,我收到了一个错误。

./test.sh: line 5: unexpected token `;', conditional binary operator expected
./test.sh: line 5: syntax error near `;'
./test.sh: line 5: `if [[ -z "$domain" && "$path"]]; then'

谢谢!

最佳答案

因为您使用的是 [[ double brackets ,您可以使用 || 来测试您的任一条件是否为真。在这种情况下,您的代码将如下所示:

#!/usr/bin/env bash
read -p "Please enter the domain Name: " domain
read -p "Please Enter path where you want to save your result: " path
if [[ -z "$domain" || -z "$path" ]]; then
echo "Either you have not entered the Domain Name, or you have not entered the path."
exit 1
else
echo "Do Something Here"
fi

请注意,括号周围的空格是必需的。正如其他人指出的那样,错误应该是具体的,所以你应该考虑这样的事情:

if [[ -z "$domain" ]]; then
echo "You have not entered the Domain Name"
exit 1
elif [[ -z "$path" ]]; then
echo "You have not entered the path"
exit 1
fi
echo "Do something here"

它有点冗长,但为用户提供了更具体的反馈。

关于linux - 如何在 bash 中读取两个输入值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54730123/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com