Bash Script to Reverse Words in a String
Use
echo "$string" | awk '{for(i=NF;i>0;i--) printf "%s%s", $i, (i==1?"\n":" ")}' to reverse words in a string in Bash.Examples
Inputhello world
Outputworld hello
InputBash scripting is fun
Outputfun is scripting Bash
Input
Output
How to Think About It
To reverse words in a string, think of splitting the string into separate words, then printing them starting from the last word to the first, joining them back with spaces.
Algorithm
1
Get the input string.2
Split the string into words based on spaces.3
Start from the last word and move to the first word.4
Print each word followed by a space except the last one.5
Return the reversed word string.Code
bash
read -r string reversed=$(echo "$string" | awk '{for(i=NF;i>0;i--) printf "%s%s", $i, (i==1?"\n":" ")}') echo "$reversed"
Output
world hello
Dry Run
Let's trace the input 'hello world' through the code
1
Input string
string = 'hello world'
2
Split into words
words = ['hello', 'world']
3
Print words in reverse
output = 'world hello'
| Iteration | Word Printed | Output So Far |
|---|---|---|
| 1 | world | world |
| 2 | hello | world hello |
Why This Works
Step 1: Splitting the string
The awk command splits the input string into fields (words) automatically.
Step 2: Looping backwards
The for loop runs from the last word (NF) to the first (1), reversing the order.
Step 3: Printing words
Each word is printed with a space except the last one, which ends with a newline for clean output.
Alternative Approaches
Using Bash arrays
bash
read -r string read -ra words <<< "$string" for (( idx=${#words[@]}-1; idx>=0; idx-- )); do printf "%s" "${words[idx]}" [[ $idx -ne 0 ]] && printf " " done printf "\n"
This uses Bash arrays and a loop, which is pure Bash but slightly longer.
Using rev and tac with process substitution
bash
read -r string echo "$string" | tr ' ' '\n' | tac | tr '\n' ' ' echo
This converts words to lines, reverses lines, then joins back, but adds a trailing space before newline.
Complexity: O(n) time, O(n) space
Time Complexity
The script processes each word once in a loop, so time grows linearly with the number of words.
Space Complexity
It stores all words temporarily, so space grows linearly with input size.
Which Approach is Fastest?
The awk one-liner is efficient and concise; Bash arrays are readable but slightly longer; using tac involves extra process calls.
| Approach | Time | Space | Best For |
|---|---|---|---|
| awk one-liner | O(n) | O(n) | Concise and fast for most cases |
| Bash arrays | O(n) | O(n) | Pure Bash, easy to understand |
| tac with tr | O(n) | O(n) | When you prefer pipeline commands |
Use
awk for a concise one-liner to reverse words in Bash.Beginners often try to reverse the whole string instead of reversing word order.