I'm trying to write a bash script to swap the words entered by the user.
For example: hello stack overflow
Output: overflow stack hello
User can enter any number of words.
I'm trying to write a bash script to swap the words entered by the user.
For example: hello stack overflow
Output: overflow stack hello
User can enter any number of words.
Take a look at the following article explaining the use of "read" in bash:
http://landoflinux.com/linux_bash_scripting_read.html
If you know ahead of time the number of words you will be switching, a simple solution could be something like this. Each word is assigned to a variable specified in your read command:
#!/bin/bash
echo "Enter two words: "
read one two
echo "first word: $one"
echo "second word: $two"
If you need to reverse a list of words in one string, you can take a look at this answer:
try this:
read -ra line # read into array
i=${#line[@]} # determine length of array
for i in $(seq $((i-1)) -1 0); do # loop in reverse order
echo -n "${line[i]} " # echo entry at i-position without linefeed
done
echo # linefeed
input
this is a test
output
test a is this