2

How assign numbers sequence into bash variable as this fail:

$ n={0..9}; echo $n
{0..9}
$ n=\"{0..9}\"; echo $n
"{0..9}"

$ eval n={0..9}; echo $n
$ eval n=\"{0..9}\"; echo $n
9

$ n=`eval {0..9}`; echo $n
bash: 0: command not found

Please guide to the correct one

1
  • 1
    What do you want n to contain? Perhaps n = "0 1 2 3 4 5 6 7 8 9", i.e. a string of numbers? Or an array of numbers? What do you want to do with this n? – berndbausch Apr 19 at 5:25
5

Assign with:

$ n=({0..9})

Using n=(x) means n is an array with x as its contents.

Then output a full array with:

$ echo "${n[@]}"
0 1 2 3 4 5 6 7 8 9

or output one element at a time with

$ for i in "${n[@]}"; do
>   printf "%s " "$i"
> done
0 1 2 3 4 5 6 7 8 9

or access a specific element with:

$ echo "${n[0]}"
0

There is lots of info already available if you search for "bash array"

3

Here's two methods:

  1. use an array

    $ n=( {0..9} )
    $ declare -p n
    declare -a n=([0]="0" [1]="1" [2]="2" [3]="3" [4]="4" [5]="5" [6]="6" [7]="7" [8]="8" [9]="9")
    
  2. expand the range into a single string

    $ n=$(printf "%s" {0..9})
    $ declare -p n
    declare -- n="0123456789"
    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.