Bash 脚本检查用户输入是否匹配特定形式

标签 bash shell ubuntu if-statement

下面你可以看到我的 bash 脚本

#createSession.sh

echo "Welcome to ADS2 Session Start..."

while [ true ]
do
echo "Starting service Daemon on the targert"
echo "Enter the ip-address of the target"
read x
if [ -z "$x" ]
then 
    echo "ip-address is empty"
else
    echo "Connecting with target..."
    if [[ $x =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]
    then
        ssh nvidia@"$x" "/opt/ads2/arm-linux64/bin/ads2 svcd&"
        echo "connection succeded"
        break
    else
        "Make sure the io address in the coorect form"  
    fi

fi
done
第一个问题
如您所见,该脚本检查用户输入是否符合 ip-address 形式。但是,我希望脚本也接受 ip 地址作为具有这种形式的字符串 fdt-c-agx-4arbitrary numbers .字符串的最后一部分可以是任意 4 个数字。结果,if语句就像if [[ $x =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] || [ $x = #machtes fdt-c-agx-4arbitrary digits] 第二个问题
IP 地址可以以正确的形式输入,但不存在。因此,在这种情况下 ssh 返回 ssh connection time out .但是字符串 connection succeded将被打印,这是不正确的。那么我怎样才能使脚本足够聪明以意识到这种情况下的连接没有建立呢?
提前感谢

最佳答案

how can i make the scripts enough clever to realize that the connection in this case is not established?


只需检查 ssh退出状态。
if ! ssh something@something something ; then
     echo "Och nuuu - problem with ssh" >&2
     exit 1
else
     echo "Yes! It worked! Good job!"
fi

As a result, the if statement be like


当然:
if 
   [[ $x =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] ||
   [[ $x =~ ^fdt-c-agx-[0-9][0-9][0-9][0-9]$ ]]
then
   ...
while [ true ]

只是:
while true
[命令检查字符串 true具有非零长度。因为有,所以成功。你可以写[ anything ]结果相同。但只是true ,它本身就是一个命令。

关于Bash 脚本检查用户输入是否匹配特定形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66705472/

相关文章:

php - 音频波形许可被拒绝bbcrd

r - macOS Big Sur 下的 Shell PATH to R

google-app-engine - 在 Ubuntu 中执行 GAE SDK 时如何解决此错误?

ubuntu - php.ini 未在 Ubuntu 16.04.3 LTS 上重新加载

Linux,如何执行可执行/不可执行文件?

regex - 将一系列日期中的 Grep 作为文件名

linux - unix下同步四个shell脚本依次运行

html - Xidel 提取标签内的数据——原始输出

具有并行 curl 操作的 Bash 脚本

bash - 如何在bash中删除多个匹配项