Given a string str, find whether the given string is palindrome or not using Bash Scripting. A string is called a palindrome string if the reverse of the string is the same as the original string.
Examples:
Input: str= “GFG”
Output: GFG is a palindrome string.
Explanation: Reverse of “GFG” is “GFG”, hence it is palindrome.
Input: bash
Output: bash is not a palindrome string.
Explanation: Reverse of “bash” is “hsab”, hence it is not palindrome.
Shell Script to Check Whether the Given String is a Palindrome or Not
#!/bin/bash
read -p “Enter a string: ” input_string
# Reverse the string and compare with the original
if [[ “$input_string” == “$(rev <<< “$input_string”)” ]]; then
echo “The entered string ‘$input_string’ is a palindrome.”
else
echo “The entered string ‘$input_string’ is not a palindrome.”
fi
Save the above script in a file, for example, example.sh
. Make it executable by running:
chmod +x example.sh
You can then execute the script:
./example.sh
Explanation:
-
`read -p "Enter a string: " input_string`
: This line prompts the user to enter a string and stores their input in the variable `input_string`
. -
`if [[ "$input_string" == "$(rev <<< "$input_string")" ]]; then`
: This line starts anif
statement. It checks if the entered string is equal to its reverse. Here’s how it works:-
`"$(rev <<< "$input_string")"`
: This part uses the `rev`
command to reverse the entered string. The `<<<`
is a “here-string” that provides the string as input torev
. -
`"${input_string}" == "$(rev <<< "$input_string")"`
: This compares the original string with its reversed version. -
If the comparison is true, the script executes the commands inside the `
then`
block.
-
-
echo "The entered string '$input_string' is a palindrome."
: If the entered string is a palindrome (i.e., it reads the same backward as forward), this line prints a message indicating that the string is a palindrome. -
else
: If the comparison in the `if`
statement is false, meaning the string is not a palindrome, the script moves to the `else`
block. -
echo "The entered string '$input_string' is not a palindrome."
: This line prints a message indicating that the string is not a palindrome.
Time Complexity: O(n) , Auxiliary Space: O(n)