Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: Increment a counter variable within a string

Tags:

bash

shell

In Bash, I'm trying to increment a counter variable (number) from within a text string. If I call the counter var alone it increments successfully, but If I echo the string variable on each iteration of my loop, the counter variable does not increment.

#!/bin/bash

number=1

yes="number$number/"

for i in 1 2 3
do
    echo $number

    echo $yes

    ((number++))

done

I get this output:

1
number1/
2
number1/
3
number1/

Whereas I expect this:

1
number1/
2
number2/
3
number3/

I have also tried this:

yes="number${number}/"

..which gave the same incorrect result.

Thanks

like image 776
Beatdown Avatar asked Aug 31 '26 13:08

Beatdown


2 Answers

for i in 1 2 3
do
    echo $number
    yes="number$number/"
    echo $yes

    ((number++))

done
like image 198
Yu Jiaao Avatar answered Sep 03 '26 07:09

Yu Jiaao


As you've been told in comments, expansion happens at the time of assignment. The variable $yes contains a string which includes the value of $number at the time of assignment. After assignment, there is nothing in the content of $yes which would indicate any connection to the variable $number.

There are two common ways to get this kind of functionality.

First, you can use eval.

#!/usr/bin/env bash

number=1

yes='number$number/'    # note the single quotes

for i in 1 2 3; do

    echo "$number"
    eval "echo \"$yes\""
    ((number++))

done

Note that the value of $yes is NOT being updated here -- it's simply being used to expand what is printed by echo.

You will find that many people discourage the use of eval, as it can have unintended security related consequences.

Second, you could just update yes each time you run through the loop.

#!/usr/bin/env bash

number=1

for i in 1 2 3; do

    echo "$number"

    yes="number$number/"
    echo "$yes"

    ((number++))

done

If you're looking to use this for formatting, then printf is your friend:

#!/usr/bin/env bash

number=1

yesfmt='number%d\n'

for i in 1 2 3; do

    echo "$number"
    printf "$yesfmt" "$number"
    ((number++))

done

Without knowing the bigger picture or what you're trying to achieve, it's difficult to recommend a strategy.

like image 22
ghoti Avatar answered Sep 03 '26 05:09

ghoti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!