Understanding Basic Logical Operations in Linux
Linux shell provides several ways to combine commands and conditions using logical operators. In this step, you will learn about the most commonly used logical operators: &&
(AND) and ||
(OR).
First, let's navigate to our project directory:
cd ~/project
Let's start by creating some test files that we'll use throughout this lab:
touch treasure_map.txt shield.txt kings_gauntlet.txt
Now, let's create a script to demonstrate basic logical operations. We'll use the nano
text editor to create a file called logic_basics.sh
:
nano logic_basics.sh
In this script, we'll use logical operators to check if two files exist. Type or paste the following code into the editor:
#!/bin/bash
## This script demonstrates logical AND (&&) and OR (||) operators
## It checks if two specific files exist in the current directory
if [[ -f "treasure_map.txt" ]] && [[ -f "shield.txt" ]]; then
echo "Both files exist. Proceed with the mission."
else
echo "One or both files are missing. Abort the mission!"
fi
The &&
operator means "AND" - both conditions must be true for the overall condition to be true.
The -f
test checks if a file exists and is a regular file (not a directory or other special file).
To save the file in nano, press Ctrl+X
, then press Y
to confirm saving, and press Enter
to confirm the filename.
Now, let's make the script executable and run it:
chmod +x logic_basics.sh
./logic_basics.sh
You should see the output:
Both files exist. Proceed with the mission.
Let's try another example to better understand logical operators. Create a new script called logical_or.sh
:
nano logical_or.sh
Add the following content:
#!/bin/bash
## This script demonstrates the logical OR (||) operator
## It checks if at least one of two files exists
if [[ -f "treasure_map.txt" ]] || [[ -f "nonexistent_file.txt" ]]; then
echo "At least one file exists."
else
echo "Neither file exists."
fi
The ||
operator means "OR" - if either condition is true, the overall condition is true.
Save the file (Ctrl+X, Y, Enter), make it executable, and run it:
chmod +x logical_or.sh
./logical_or.sh
Output:
At least one file exists.
This demonstrates that even though "nonexistent_file.txt" doesn't exist, the condition is still true because "treasure_map.txt" does exist.