In Linux shell scripting, conditions are often used to analyze various scenarios and make decisions based on the results. Here's how you can use conditions to analyze different situations, along with examples demonstrating the commands, options, and syntax used:
#!/bin/bash
echo "Enter a number:"
read NUM
if (( NUM % 2 == 0 )); then
echo "$NUM is even."
else
echo "$NUM is odd."
fi
#!/bin/bash
echo "Enter an email address:"
read EMAIL
if [[ "$EMAIL" =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then
echo "$EMAIL is a valid email address."
else
echo "$EMAIL is not a valid email address."
fi
The regular expression ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$ ensures that the email address follows the standard format:
- Starts with one or more alphanumeric characters, periods, underscores, percentage signs, plus signs, or hyphens ([a-zA-Z0-9._%+-]+).
- Followed by an '@' symbol.
- Followed by one or more alphanumeric characters, periods, or hyphens ([a-zA-Z0-9.-]+).
- Followed by a period ('.').
- Ends with two or more alphanumeric characters (e.g., .com, .org, .edu) ([a-zA-Z]{2,}).
#!/bin/bash
echo "Enter a URL:"
read URL
if curl --output /dev/null --silent --head --fail "$URL"; then
echo "$URL is a valid URL."
else
echo "$URL is not a valid URL."
fi
The curl command is used to send a HEAD request to the specified URL. The options used with curl are:
- --output /dev/null: Redirects the output to /dev/null, suppressing any output.
- --silent: Runs in silent mode, suppressing progress meter and error messages.
- --head: Sends a HEAD request, retrieving only the headers of the URL.
- --fail: Makes curl return a non-zero exit status if the request fails.
If the curl command succeeds (i.e., the URL is reachable), it returns a zero exit status, and the script displays a message indicating that the URL is valid. If the curl command fails (i.e., the URL is unreachable or invalid), it returns a non-zero exit status, and the script displays a message indicating that the URL is not valid.
#!/bin/bash
echo "Enter a number:"
read NUM
if (( NUM > 0 )); then
echo "$NUM is positive."
elif (( NUM < 0 )); then
echo "$NUM is negative."
else
echo "$NUM is zero."
fi
#!/bin/bash
echo "Enter a file path:"
read FILE
if [[ -w "$FILE" ]]; then
echo "$FILE is writable."
else
echo "$FILE is not writable."
fi
#!/bin/bash
echo "Enter a file path:"
read FILE
if [[ -e "$FILE" ]]; then
echo "$FILE exists."
else
echo "$FILE does not exist."
fi
#!/bin/bash
echo "Enter a directory path:"
read DIR
if [[ -d "$DIR" ]]; then
echo "$DIR exists."
else
echo "$DIR does not exist."
fi
These examples demonstrate how to use conditions in Linux shell scripts to analyze different scenarios such as determining if a number is even or odd, validating email addresses and URLs, checking if a number is positive or negative, verifying file and directory existence, and more.