How to convert string to int in bash?

I want an array containing numbers from 1 to twice as many lines in a text file. In this example, the file somefile.dat has four lines. I tried:

~$ echo {1..$(( `cat somefile.dat | wc -l`*2 ))}
{1..8}

      

which I didn't want. However, what happens inside the parenthesis is explicitly interpreted as integers. Why then, is the final result a string? And how do I convert it to int so that I get the digits 1 through 8 as output?

+3


source to share


1 answer


Why then, is the final result a string?

This is because the parenthesis range directive in the shell {1..10}

does not support a variable in it.

According to man bash

Brace expansion is performed before any other extensions , and any characters special to other extensions are preserved in the result. It is strictly textual. Bash does not parse the extension context or the text between curly braces.



<strong> Examples:

echo {1..8}
1 2 3 4 5 6 7 8

n=8
echo {1..$n}
{1..8}

      

Alternatively, you can use seq

:

seq 1 $n
1
2
3
4
5
6
7
8

      

+4


source







All Articles