To reverse a string in the Bash shell, the most common and efficient method is using a for loop or, for a more modern approach, an external command like rev. Bash doesn’t have a built-in function specifically for string reversal, so you’ll typically use a loop to iterate over the characters.
Method 1: Using a for Loop
A for loop is a robust way to reverse a string by iterating through it character by character from the end to the beginning. This method is pure Bash and doesn’t require any external tools, making it very fast.
Example
my_string="Hello"
reversed_string=""
# Iterate from the last character to the first
for (( i=${#my_string}-1; i>=0; i-- )); do
# Append each character to the new string
reversed_string+="${my_string:i:1}"
done
echo "$reversed_string"
# Output: olleH
my_string="Hello": Defines the original string.i=${#my_string}-1: Initializes the loop counterito the index of the last character.${#my_string}gives the length of the string, and subtracting 1 gives the last index.i>=0: The loop continues as long asiis a valid index (greater than or equal to 0).i--: Decrements the counter for each iteration.reversed_string+="${my_string:i:1}": This is the core of the operation.my_string:i:1: Uses parameter expansion to extract a substring of length 1 at indexi.+=: Appends this single character to thereversed_stringvariable.
Method 2: Using the rev Command
The rev command is a simple, dedicated utility for reversing lines of text. It’s often included with most Linux and Unix systems. This method is the simplest and most readable, especially for one-off operations.
Example
my_string="Bash Scripting"
# Pipe the string to the 'rev' command
reversed_string=$(echo "$my_string" | rev)
echo "$reversed_string"
# Output: gnitpircS hsaB
echo "$my_string": Prints the string to standard output.|: Pipes the output ofechoto the standard input of therevcommand.rev: Reads the input and prints the reversed string to standard output.$(): Captures the output of the command and assigns it to thereversed_stringvariable.
Method 3: Using awk
While not as direct as rev, awk can also be used for string reversal. It’s more useful if you’re already using awk for other text processing tasks.
Example
my_string="programming"
reversed_string=$(echo "$my_string" | awk '{
for (i=length; i>0; i--) {
r=r substr($0, i, 1)
}
print r
}')
echo "$reversed_string"
# Output: gnimmargorp
length: A built-inawkvariable that holds the length of the current record (the string).substr($0, i, 1): Extracts a single character from the input string ($0) at the current indexi.r=r ...: Builds the reversed string by concatenating each character.
For most cases, using rev is the most straightforward and elegant solution, while the for loop method is best when you need a pure Bash solution without external dependencies.