Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Learn Linux Quickly

You're reading from   Learn Linux Quickly A beginner-friendly guide to getting up and running with the world's most powerful operating system

Arrow left icon
Product type Paperback
Published in Aug 2020
Publisher Packt
ISBN-13 9781800566002
Length 338 pages
Edition 1st Edition
Tools
Arrow right icon
Author (1):
Arrow left icon
Ahmed AlKabary Ahmed AlKabary
Author Profile Icon Ahmed AlKabary
Ahmed AlKabary
Arrow right icon
View More author details
Toc

Table of Contents (24) Chapters Close

Preface 1. Your First Keystrokes 2. Climbing the Tree FREE CHAPTER 3. Meet the Editors 4. Copying, Moving, and Deleting Files 5. Read Your Manuals! 6. Hard versus Soft Links 7. Who Is Root? 8. Controlling the Population 9. Piping and I/O Redirection 10. Analyzing and Manipulating Files 11. Let's Play Find and Seek 12. You Got a Package 13. Kill the Process 14. The Power of Sudo 15. What's Wrong with the Network? 16. Bash Scripting Is Fun 17. You Need a Cron Job 18. Archiving and Compressing Files 19. Create Your Own Commands 20. Everyone Needs Disk Space 21. echo "Goodbye My Friend" 22. Assessments 23. Other Books You May Enjoy

Using the if condition

You can add intelligence to your bash script by making it behave differently in different scenarios. To do that, we use the conditional if statement.

In general, the syntax of the if condition is as follows:

if [ condition is true ]; then 
do this ...
fi

For example, let's create a script empty.sh that will examine whether a file is empty or not:

elliot@ubuntu-linux:~$ cat empty.sh 
#!/bin/bash
filesize=$(du -bs $1 | cut -f1)
if [ $filesize -eq 0 ]; then
echo "$1 is empty!"
fi

Now let's make the script executable and also create an empty file named zero.txt:

elliot@ubuntu-linux:~$ chmod a+x empty.sh 
elliot@ubuntu-linux:~$ touch zero.txt

Now let's run the script on the file zero.txt:

elliot@ubuntu-linux:~$ ./empty.sh zero.txt 
zero.txt is empty!

As you can see, the script correctly detects that zero.txt is an empty file; that's because the test condition is true in this case as the file zero.txt is indeed zero bytes in size:

if [ $filesize...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image