下面你可以看到我的 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/