Here is a simple example of an if-else statement in a shell script: Bash
#!/bin/bash
# Check if the file "myfile.txt" exists
if [ -f myfile.txt ]; then
# The file exists
echo "The file myfile.txt exists."
else
# The file does not exist
echo "The file myfile.txt does not exist."
fi
Use code with caution. Learn more
This script will check if the file "myfile.txt" exists. If it does, the script will print the message "The file myfile.txt exists." Otherwise, the script will print the message "The file myfile.txt does not exist."
Here is another example of an if-else statement in a shell script:
Bash
#!/bin/bash
# Get the current user's name
username=$(whoami)
# Check if the current user is root
if [[ "$username" == "root" ]]; then
# The current user is root
echo "You are logged in as root."
else
# The current user is not root
echo "You are not logged in as root."
fi
Use code with caution. Learn more
This script will get the current user's name and then check if the current user is root. If the current user is root, the script will print the message "You are logged in as root." Otherwise, the script will print the message "You are not logged in as root."
If-else statements can be used to control the flow of your shell scripts. By using if-else statements, you can execute different code depending on the value of a condition.