3

Hello I want my script to output the following:

string1 string2
string1 string2 string2
string1 string2 string2 string2
string1 string2 string2 string2 string2

Etc. for about 20 times or so.

I've tried the following:

#! /bin/bash
string1=hello
string2=world

#for {i=1;i=<10;i=i+1};
#echo $string1 + $string2
#!/bin/bash
for ((number=1;number < 10;number++))
do
echo $string1 $string3
string2 *10
done;
exit 0

Now I can't find anything on the web about just looping and adding strings.. Thanks for any help! Greets

5
  • 1
    s1="hello";s2="world"; for i in {1..10}; do s1="$s1 $s2"; echo $s1; done Commented Feb 7, 2018 at 14:10
  • 1
    @gtato Please don't use brace expansions for iteration. Either use the C-style for loop as seen in the question, or use a while loop for POSIX compatibility. Commented Feb 7, 2018 at 14:18
  • @chepner: Oops... First time I heard about that POSIX compatibility. Commented Feb 7, 2018 at 14:22
  • hi @chepner, what about for i in $(seq 10) ? Commented Feb 7, 2018 at 14:27
  • 2
    That's worse; now you have an external process generating the full list of values up front instead of having the shell doing it internally. (I should say, {...} is OK for generating non-sequential ranges like {foo,bar,baz}.{txt,png,gif}. Just don't use it for "predictable" sequences you can generate from a formula in constant space.) Commented Feb 7, 2018 at 14:37

2 Answers 2

2

Your bash syntax is not correct.

#!/bin/bash

string1=hello
string2=world
output=$string1" "$string2

for i in {1..10} ; do
  echo $output
  output=$output" "$string2
done

Edit: or, taking into account the comments below for the sake of beauty of code:

#!/bin/bash

string1="hello"
string2="world"
output="$string1 $string2"

for ((i = 1; i <= 10; i++)) ; do
  echo "$output"
  output+=" $string2"
done
Sign up to request clarification or add additional context in comments.

4 Comments

Hi, you also can do this: output+=" $string2"
output="$string1 $string" would be the more idiomatic quoting style.
The other quoting errors should also be fixed. shellcheck.net can provide more detailed diagnostics.
With string1+=" $string2" before the echo you can skip both lines with output. Disadvantage of this, is that the value of string1 is changed.
1

you can do this by writing to a variable, appending to it in an inner loop and then echo it out:

string1="string1"
string2="string2"
for ((i=1;i<=10;i++)); do
  output="$string1"
  for ((j=1;j<=$i;j++)); do
    output+=" $string2"
  done
  output+=
  echo $output
done

1 Comment

bash also supports a more concise += operator: output+=" $string2". (Prefer lowercase variables to all-uppercase, which are reserved for the shell.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.