LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (http://www.linuxquestions.org/questions/linux-software-2/)
-   -   Shell: string1 += string2. How to do this? (http://www.linuxquestions.org/questions/linux-software-2/shell-string1-%3D-string2-how-to-do-this-562994/)

jhwilliams 06-19-2007 12:46 PM

Shell: string1 += string2. How to do this?
 
!/bin/sh

I would like to do the following operation on strings in shell (concatenate w/ a space):

Code:


string1='ham butter ham'
string2='donut'
string1 += $string2
echo $string1

to yield "ham butter ham donut" as the output. how do I do this?

PatrickNew 06-19-2007 12:50 PM

try
Code:

string1=${string1} ${string2}

jhwilliams 06-19-2007 12:57 PM

Didn't work for me. Here's my code if it helps... Thanks.

Code:

dir_list=`ls -ad */ 2>/dev/null`
cleaned_dirs=''

for dir_name in $dir_list ; do
    cd $dir_name
    # ... some stuff...
    if [ $? ]; then
        cleaned_dirs=${cleaned_dirs} ${dir_name}
    fi
    cd ..
done


PatrickNew 06-19-2007 01:13 PM

Sorry, I should have known better. /bin/sh isn't taking kindly to the whitespace. It should be something like this
Code:

string1="$string1 $string2"

dawkcid 06-19-2007 01:13 PM

Try using an array.

diff:

Code:

cleaned_dirs=()

        cleaned_dirs=(${cleaned_dirs} ${dir_name})

Code:

string1 += $string2
has spaces around the +=, which is wrong. You cannot put spaces around an assigment operator in the shell. Bash doesn't understand += anyway (some shells do though).

Code:

string1=${string1} ${string2}
fails for the same reason, a space between string1 and string2 (this tries to run the command $string2). It should be

Code:

string1="${string1} ${string2}"
But, as I said, you should be using an array for this purpose (a list of seperate directories).

PatrickNew 06-19-2007 01:18 PM

the array may not really be necessary if he is only building this list in order to pass it as the arguments to a command. Then an array may only complicate the things. This scenario isn't unlikely in a shell script.

To the OP, dawkcid caught my mistake at the same time I did, but you should use the code in my post, as dakwcid's concatenates the strings without a space in between them.

dawkcid 06-19-2007 01:49 PM

Quote:

Originally Posted by PatrickNew
the array may not really be necessary if he is only building this list in order to pass it as the arguments to a command. Then an array may only complicate the things. This scenario isn't unlikely in a shell script.

Oh, I was assuming it was intended just for logging/reporting which directories had been processed. So, yeah, a string may be preferable depending on what you want to do with it.

Quote:

To the OP, dawkcid caught my mistake at the same time I did, but you should use the code in my post, as dakwcid's concatenates the strings without a space in between them.
Yeah, that was a typo, I fixed it.


All times are GMT -5. The time now is 05:05 AM.