Testing strings

We can test for the equality or inequality of two strings. For example, one of the ways to test the root user is using the following command:

test $USER = root  

We could also write this using the square bracket notation:

[ $USER = root ]  

Note that you must put a space between each bracket and the inner testing condition as previously shown.

Equally, we could test for a non-root account with the following two methods:

test ! $USER = root
[ ! $USER = root ] 

We can also test for the zero values or non-zero values of strings. We saw this in an earlier example in this chapter.

To test if a string has a value, we can use the -n option. We can check to see if the current connection is made through SSH by checking for the existence of a variable in the user's environment. We do this by using test and square brackets in the following two examples:

test -n $SSH_TTY
[ -n $SSH_TTY ]  

If this is true, then the connection is made with SSH; if it is false, then the connection is not through SSH.

As we saw earlier, testing for a zero string value is useful when deciding if a variable is set:

test -z $1 

Or, more simply, we could use the following:

[ -z $1 ]  

A true result for this query means that no input parameters have been supplied to the script.