04. String Tests =, !=

String tests can be useful for checking user's input.

Checking for string equality

To check if two strings are equal or not, simply use the = or != operators.

$ [ 'hi' = 'hi' ]; echo $?
0
$ [ 'hello' = 'hi' ]; echo $?
1

Checking if argument is empty or not

Two unary operators are used to check if a string is empty or not.

-z
Argument is empty
-n
Argument is not empty
$ [ -z "" ]; echo $?
0
$ [ -n "" ]; echo $?
1

Example script

Here's a simple script that reads an input, and depending on the string put in, returns a specific response.

#!/bin/bash
 
printf 'Please enter a word: '
 
read input
 
if [ $input = 'hi' ]; then
  printf 'Hi to you too!'
else
  printf 'You input %s.\n' $input
fi

We'll go over if-then-else statements soon, but notice how we can use tests and expressions such as these to control logic in our scripts.

Take your Linux skills to the next level!

How Linux Works

Take your Linux skills to the next level! Try Linux & UNIX

In this completely revised second edition of the perennial best seller How Linux Works, author Brian Ward makes the concepts behind Linux internals accessible to anyone curious about the inner workings of the operating system. Inside, you'll find the kind of knowledge that normally comes from years of experience doing things the hard way.

$ Check price
39.9539.95Amazon 5 logo(114+ reviews)

More Linux & UNIX resources

Aching back from coding all day?

Inversion Therapy Table

Aching back from coding all day? Try Back Problems

Stretch out your back and relieve your back muscles with inversion therapy. This device counteracts the forces of gravity on the body by decompressing and elongating the spine. By using this product just ten minutes a day, you can be well on your way to improved circulation and posture while relieving muscle aches, back pain and stress.

$$ Check price
119.98119.98Amazon 4.5 logo(1,700+ reviews)

More Back Problems resources

Ad