Khaled
Khaled

Reputation: 563

Bash script check if user-input matches certain form

Below you can see my bash script

#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

First question

As you see, the script checks if the user input machtes the ip-address form. However, i would like the script to also accept the ip address as a string which has this form fdt-c-agx-4arbitrary numbers. The last part of the string can be any arbitrary 4 numbers. As a result, the if statement be like

if [[ $x =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] || [ $x = #machtes fdt-c-agx-4arbitrary digits]

Second question

The ip address could be entered in the right form, however does not exist. Consequently, the ssh returns in this case ssh connection time out. However the string connection succeded will be printed which is not true. So how can i make the scripts enough clever to realize that the connection in this case is not established?

Thnaks in advance

Upvotes: 0

Views: 380

Answers (1)

KamilCuk
KamilCuk

Reputation: 141020

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

Just check the ssh exit status.

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

Sure:

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 ]

Just:

while true

The [ command checks if the string true has nonzero length. Because it has, it's a success. You could write [ anything ] with same result. But just true, it's a command on it's own.

Upvotes: 2

Related Questions