【问题标题】:Bash script check if user-input matches certain formBash 脚本检查用户输入是否匹配特定形式
【发布时间】:2021-03-19 09:19:51
【问题描述】:

下面你可以看到我的 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 将被打印出来,这是不正确的。那么我怎样才能让脚本足够聪明地意识到这种情况下的连接没有建立呢?

提前问好

【问题讨论】:

  • As a result, the if statement be like Soo...这样写?您以^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ 为例,因此只需编写与另一个匹配的相同内容即可。
  • 那么您认为[0-9] 是什么意思?我推荐网络上提供的正则表达式填字游戏,以便立即学习正则表达式。
  • @KamilCuk 你写的。 0 到 9 之间的数字

标签: bash shell ubuntu if-statement


【解决方案1】:

我怎样才能让脚本足够聪明地意识到这种情况下的连接没有建立?

只需检查ssh 退出状态。

if ! ssh something@something something ; then
     echo "Och nuuu - problem with ssh" >&2
     exit 1
else
     echo "Yes! It worked! Good job!"
fi

结果,if 语句就像

当然:

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,它本身就是一个命令。

【讨论】:

  • 感谢您的详细解答。但是,OR 运算符似乎不起作用。我独立尝试了每个条件并且它有效。但是,使用 or 更有效。我是否错误地使用了 or 运算符?
  • 对于监听 ssh,当 ip 地址正确时,它会再次询问密码,就像它再次调用连接一样
  • 我用 OR 运算符解决了这个问题。但是关于监听 ssh 退出状态的 if 语句提示用户再次输入密码
  • if statement regarding listening to ssh exit status prompts the user to enter the password again 所以?这很好 - 您应该在连接到远程服务器之前验证自己。如果您不想提供密码,请研究公钥身份验证,即。 ssh-copy-id。如果您希望您的凭据被缓存,请研究 ssh-agent 和可能的 ssh 的 ControlMaster 选项。
  • 没错。但是,它在检查 IP 地址后已经询问并远程执行命令。为什么当我观察到 ssh 退出时它会再次询问?。
猜你喜欢
  • 1970-01-01
  • 2021-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-02
  • 2011-09-22
相关资源
最近更新 更多