Last Updated:

Bash Control Statements

cp /etc/foo .
echo "Done"


This is a small script, let's call it, copies a file named /etc/foo to the current directory and displays "Done" on the screen. This program will work under one condition - the /etc/foo file must exist. Otherwise, here's what will happen:

cp: /etc/foo: No such file or directory


So, as you can see, there is a problem. Not everyone who runs your program will have a /etc/foo file. Probably, it would be better if your program first checked for the presence of this file, and then, if the answer was positive, it would perform a copy, otherwise it would simply shut down. In the pseudo-code, it looks like this:

if /etc/foo exists, then
copy /etc/foo to
the current directory print "Done" on the screen
print on the screen "This file does not exist"

Is it possible to do this in Bash? Of course! The set of Bash control statements includes:if, while, until, for, and case. Each of these operators is paired, that is, it begins with one tag and ends with another. For example, if a conditional if statement starts with if and ends with fi. Control statements are not separate programs in the system, they are built into bash.