Yokai Seishinkage Yokai Seishinkage - 1 year ago 72
Bash Question

Read a single word from a string and set as a variable value in bash

I have a need for a simple function to do the following:


select_word() {

echo "Enter a string."

## User enters "This is a string."

## Here will be the command to set each word to the below variables.


echo -e "Word 1 is: $WORD_1.\n Word 2 is: $WORD_2.\n"
echo -e "Word 3 is: $WORD_3.\n Word 4 is: $WORD_4.\n"

I am wanting to avoid using external tools such as sed or awk. Looking for bash builtin functions to use in order to pull each word from the string and set that word as a variable. I will later use "wc" to count the number of characters in each word. I already know how to do that, I just need to know the bash method to pulling a word from user input strings.

If this question is a duplicate, I apologize as I could not find this specific question.

Answer Source

You can convert the space delimited $STRING into an array, and then reference each array element in $WORD_n variables:


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download