150k views
4 votes
Write a Linux script that tests whether a string is a palindrome. (A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward.)

User TheLuminor
by
8.1k points

1 Answer

7 votes

Final answer:

A bash script can be used to check if a string is a palindrome by removing spaces and punctuation, converting it to lowercase, and comparing it with its reverse. Save the script, give it execute permissions, and run it to test strings.

Step-by-step explanation:

Creating a Script to Check for Palindromes

To test whether a string is a palindrome, you can write a simple script in Linux. Below is a step-by-step guide to create a bash script that determines if a string is a palindrome.


  1. Start by opening your text editor and create a new file named palindrome_checker.sh.

  2. Type the following code into the file:

#!/bin/bash
read -p "Enter a string: " str
str_clean=$(echo $str | tr -d '[:space:]' | tr -d '[:punct:]' | tr '[:upper:]' '[:lower:]')
str_reversed=$(echo $str_clean | rev)

if [ "$str_clean" == "$str_reversed" ]; then
echo "The string is a palindrome."
else
echo "The string is not a palindrome."
fi


  1. Save the file and give it execute permissions using the command chmod +x palindrome_checker.sh.

  2. Run the script by typing ./palindrome_checker.sh and then enter the string you want to check.

This script will prompt the user to enter a string, it then removes spaces and punctuation, converts all characters to lowercase, and compares the cleaned string to its reverse. If they are identical, the script will output that the string is a palindrome.

User Kenneth Chu
by
8.7k points