1

I want to define numbered string in series in bash such as follows:

String1
String2
String3
String4
String5

What I did till now is as follows which it does not work well.

#!/bin/bash
str_name='String'
for i in `seq 1 5`
do
expr=$(($str_name + $i)) #this part is what I cannot deal with it.
echo $expr
done

Thanks

2
  • "it does not work well" - you'd help the guys here by saying what doens't work! f.e.: Error Messages? What is the output you get? Commented Jun 20, 2016 at 23:32
  • 1
    printf "%s\n" "String"{1..5}? Commented Jun 21, 2016 at 0:09

3 Answers 3

1

What you're doing is adding variables in an arithmetic sense. You want to use the following:

expr="${str_name}${i}"

Note: It's not necessary to surround the variables with brackets. I just do it because it's easier to read sometimes, it also keeps me from making stupid mistakes.

To go into more detail, $(...) executes anything between the parentheses in a sub-shell and returns the results. I'm not sure what output you where getting when echoing $expr, but I gather it was an error message. Something like Command String + 1 cannot be found but I really don't know.

Sign up to request clarification or add additional context in comments.

2 Comments

No errors: here it's not about $( ... ) but about $(( ... )), which is an arithmetic expansion, not a command substitution. In OP's case, String is undefined, hence expands to 0 in arithmetic, so the expansion $expr is 1, 2, 3, 4, 5 respectively.
You're completely right @gniourf_gniourf - don't know what I was thinking. I'll edit my last paragraph out. Do you mind if I add your comment to my answer, with attribution?
0

You even don't require echo in another line. try this.

#!/bin/bash
str_name='String'
for i in `seq 1 5`
do
echo $str_name$i
done

Comments

0

Brace Expansion is another manner in which you can iterate over a range:

for i in {1..5}; do
    printf "String%d\n" $i
done

For example:

$ for i in {1..5}; do printf "String%d\n" $i; done
String1
String2
String3
String4
String5

Comments

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.