Bash Script 5: Ifs/Tests

Published On: Wednesday, October 31st 2018
Almost every program contains some sort of logical test. This could be just checking to see if it's a certain time, or if the user enter Y or N. Bash scripting offers a wide variety of tests. Let's go over some of what's possible here.

Basic If Structure

If we're going to be doing a test, we want the program to respond one way if it's true and another way if it's false. This is accomplished with the if/then/else/fi bash control structure. Here's a simple example: [bash] if [ "1" -eq "1" ] then echo "1 equals 1"; else echo "1 does not equal 1"; fi [/bash] Here we are checking to see if 1 equals 1. Since it does, the code between then and else will be executed. If the test were to be false, then the code between else and fi would be executed.

Number Tests

Let's say you want to run some checks on 2 numbers. Here are the tests you can run: [bash] a=1 b=2 # Test for equality if [ "$a" -eq "$b" ] then echo 'They are equal'; fi # Test for a note qual to b if [ "$a" -ne "$b" ] then echo 'a is not equal to b'; fi # Test for a greater than b if [ "$a" -gt "$b" ] then echo 'a is greater than b'; fi # Test for a lesser than b if [ "$a" -lt "$b" ] then echo 'a is lesser than b'; fi [/bash]

String Tests

Comparing 2 strings is very useful too. [bash] a="asdf" b="fdsa" # Test for a equal to b if [ "$a" = "$b" ] then echo 'a and b are the same' fi # Test for a not equal to b if [ "$a" != "$b" ] then echo 'a and b are not the same' fi # Test if the contents of a comes before b, alphabetically if [[ "$a" < "$b" ]] then echo 'The contents of a come before b' fi # Test if a is empty if [ -z "$a" ] then echo 'a is empty' fi # Test if a is not empty if [ -n "$a" ] then echo 'a is not empty' fi [/bash]

Other Tests

There are other tests you can perform as well: [bash] # Check for a file's existence if [ -f my_file.mkv ] then echo 'Found my_file.mkv'; else echo 'Cannot find my_file.mkv'; fi # Check for non-zero filesize if [ -s my_file.mkv ] then echo 'File has contents' fi # Check if a filename is really a directory if [ -d my_file.mkv ] then echo 'my_file.mkv is really a directory' fi [/bash]

Tag Cloud

Copyright © 2024 Barry Gilbert.