Getting started with scripting on Linux: Testing variables

if [ $ans == "yes" ]; then
    echo "OK, let's get going"
else
    exit
fi

There are, however, quite a few tests that you can run – whether strings are the same or not and even how they relate alphabetically. The script below compares two strings in many ways.

#!/bin/bash

echo -n "Enter first string: "
read str1
echo -n "Enter second string: "
read str2
echo

# run tests to see how strings relate
if [ "$str1" = "$str2" ]; then echo strings are the same; fi
if [ "$str1" == "$str2" ]; then echo strings are the same; fi
if [ "$str1" != "$str2" ]; then echo "$str1" and "$str2" differ; fi
if [ "$str1" < "$str2" ]; then echo "$str1" comes first alphabetically; fi
if [ "$str1" > "$str2" ]; then echo "$str2" comes first alphabetically; fi
if [ -z "$str1" ]; then echo string1 is null; fi
if [ -z "$str2" ]; then echo string2 is null; fi
if [ -n "$str1" ]; then echo string1 is not null; fi
if [ -n "$str2" ]; then echo string2 is not null; fi

In some of the tests above, characters are inserted before quotes to ensure that the strings are displayed within quote marks.

Here’s a script that uses this test.

#!/bin/bash

echo -n "enter a year&gt; "
read year
this_year=`date +%Y`			# get current year using the date command

if [ "$year" -lt $this_year ]; then
    diff=`expr $this_year - $year`
    echo "Wow, that was $diff year{s} ago"
elif [ "$year" -gt $this_year ]; then
    diff=`expr $year - $this_year`
    echo "Only $diff year(s) to go"
else
    echo "$year is current year"
fi

Notice that the script above uses if, else if and else logic instead of several independent if tests.

You can also try to collect mis-entered data with commands like these that will loop until a proper year is entered.

#!/bin/bash

echo -n "Enter year&gt; "
read year

re="^[0-9]+$"
while ! [[ $year =~ $re ]]
do
    echo "error: Year must be numeric"
    echo -n "year&gt; "
    read year
done

The examples above are fairly advanced. They set up a numeric expression that will match any string of digits. If it doesn’t match (the “!” in the script means “not”), an error will be displayed and the script will continue looping until it does.



Source link