LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Bash: Problem to prepend text to variable (https://www.linuxquestions.org/questions/programming-9/bash-problem-to-prepend-text-to-variable-788892/)

Beaverfriend 02-13-2010 09:25 AM

Bash: Problem to prepend text to variable
 
The output of following code is not like it's intended ...
Code:

echo "Test prepending ..."

for words in "apple" "hour"
        do
                prepended="an $prepended $(echo "$words")"
done

echo $prepended
echo "---"


echo "Test appending ..."
for words in "apple" "hour"
        do
                appending=("$appending $(echo "$words") is a nice word,")
done

echo $appending

This is the output:
Code:

Test appending ...
an an apple hour
---
Test prepending ...
apple is a nice word, hour is a nice word,

But of course what I want to do in the first set of commands is to prepend the word "an" to the words "apple" and "hour" in the for-loop.

Would be very grateful for any clues! Thanks in advance!

tuxdev 02-13-2010 09:44 AM

This has several issues:
1. Misuse of quotes. You don't need to quote the items to loop through, but you *do* need to quote any expansion (echo "$appended" and echo "$prepended")
2. Useless use of echo. "$(echo "$words")" is equivalent to just "$words"
3. The prepended=("...") construct creates an *array* of one item and assigns it to the variable prepended. Probably not what you want to do.

Please throw out whatever it is you're trying to use to learn and read this:
http://mywiki.wooledge.org/BashGuide

Beaverfriend 02-13-2010 09:45 AM

Sorry for confusing prepend with append. See edit in last post.

Beaverfriend 02-13-2010 09:53 AM

Thanks for your reply!

Actually, the stupid example is my own invention :)

What would be a working way to prepend a string to the items in the for-loop?

Beaverfriend 02-13-2010 10:12 AM

This works as intended:

Code:

for words in apple hour
    do
        prepended="$prepended an $words"
done

echo $prepended

Problem was that I was putting the word to prepend ("an") before the $prepended-variable, which contains the collected that has already had "an" prepended to them. What I wanted to do was to prepend earlier prependations to the result of the latest. Code above does that.

Removed useless echos and quotes as tuxdev suggested.


All times are GMT -5. The time now is 09:02 PM.