daemoner119
daemoner119

Reputation: 113

bashrc - want to append to a variable

I know in C++, you can do the following:

string Var = "";
for(int i=0; i<15; i++){
    Var=std::to_string(i) + " ";
    Var+=Var; 
}
cout << "Var: " << Var << endl;

The end result would be: "Var: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14".

How would I achieve the following in a bashrc script?

Upvotes: 1

Views: 228

Answers (2)

mklement0
mklement0

Reputation: 440637

choroba's answer works well with a fixed iteration count, but won't work with variables, because the sequence form of Bash's brace expansion feature ({0..14}) only works with literals.

Thus, using Bash's C-style arithmetic loop is generally preferable:

var=''
count=15  # variable iteration count
for (( i = 0; i < count; ++i )); do # note that vars. need no $ inside (( ... ))
  var+="$i " # append, using string interpolation (in *double* quotes)
done
echo "Var: $var" # double-quote what to echo to prevent unwanted interpretation.

Upvotes: 1

choroba
choroba

Reputation: 242423

#! /bin/bash
var=''
for i in {0..14} ; do
    var+=$i' '
done
echo Var: $var

Upvotes: 2

Related Questions