Hesam
Hesam

Reputation: 11

Numbered string in bash Linux

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

Upvotes: 1

Views: 46

Answers (3)

David C. Rankin
David C. Rankin

Reputation: 84541

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

Upvotes: 0

sumitya
sumitya

Reputation: 2691

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

Upvotes: 0

Jonny Henly
Jonny Henly

Reputation: 4213

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.

Upvotes: 1

Related Questions