0

I am trying to print an array which contains string elements. Some are words, some are number and some have both. I get the error in the title. I know this error is usually linked to the shell thinking I am using a base other than decimal. this time the problem token is a combination of letters and numbers (2M)

arrcourse=[$[`cat tmp2`]]
    size=${#arrcourse[@]}
    for(( j=1; j<$size; j++ )); do
        echo ${arrcourse[$j]}
    done

tmp2 is the file the contains the line I ultimately wanna print (I use and array to lose the spaces and later to choose which elements to print).

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
doronbs11
  • 15
  • 1
  • 4

2 Answers2

0

The first line looks suspicious. Arrays are created with parenthesis (), not braces []. Did you want to write one of the following commands instead?

arrcourse=(`cat tmp2`)
arrcourse=( $(cat tmp2) )

The commands are equivalent. $() is preferred over backticks because it can be nested.

Hint: Bash also has a command to read arrays.

read -ra arrcourse < tmp2
Socowi
  • 25,550
  • 3
  • 32
  • 54
  • @doronbs11 Glad I could help. Please accept the answer that solved your problem (click the checkmark on the left of an answer) to close your question. – Socowi Nov 09 '17 at 21:51
  • 1
    I'd recommend the `read` option -- using `$( )` without double-quotes around it doesn't just split it into "words" based on whitespace (spaces, tabs, and newlines, assuming you haven't changed `$IFS`), it also tries to expand anything that looks like a shell wildcard into a list of matching filenames. This can have really weird effects. (And, of course, if you do use double-quotes, it won't be word-split and you just get the entire file as one huge array element.) – Gordon Davisson Nov 09 '17 at 22:14
0

Why not just do this?

printf '%s\n' "${my_array[@]}"

Source: bash print array elements on separate lines

R4F6
  • 782
  • 1
  • 9
  • 26