0

Is it possible to cat array elements that are text files passed as input? I have something like this:

array=("$@")
cat array[3]

Where first I put all my arguments (some files.txt) into an array to handle them later and then for example I'd like to print the body of the third file (I know I could easily use cat $3).

Luca
  • 95
  • 1
  • 8
  • It is possible, but you are dereferencing the array elements in a wrong way. The correct syntax is cat "${array[3]}"; have a look at shellcheck to prevent this kind of syntax errors in shell scripts. Addendum: numbering of array indices startes at 0 unless manually specified. – AdminBee Apr 14 '20 at 09:35
  • @AdminBee Yes you are right, thanks. – Luca Apr 14 '20 at 09:37

1 Answers1

2

The syntax for accessing a particular element of an array is

${var[index]}

where index is an expression that evaluates to an integer between zero and the length of the array, minus 1 (array indexes in bash are zero-based).

To get $3 from your array, use ${array[2]}, i.e.

cat <"${array[2]}"

See also

You would use array[3] in an assignment:

array[3]=something

This would assign the string something to the fourth element in the array.

Also related to the fact that bash arrays start at zero:

Kusalananda
  • 333,661
  • Thank you for your answer. I tried as you said but apparently it gives me the error "cat: ' ': File or directory does not exist" even though the file I'm passing to the script is inside that directory. – Luca Apr 14 '20 at 09:50
  • @Luca Your array contains a single space in that array element. You will have to show 1) your actual and complete code, including the invocation of the script, and 2) that the file is available. Please update your question. Also, the cat command usually says "No such file or directory". Did you translate the error message yourself? – Kusalananda Apr 14 '20 at 09:55
  • ♦ No problem, solved it. I was simply cat-ing an empty array cell. Thank you. – Luca Apr 14 '20 at 09:58
  • In bash where arrays are sparse like in ksh which it tries to emulate, array[3]=something would only assign something to the "fourth" element if the elements of index 0, 1 and 2 were also set. – Stéphane Chazelas Apr 14 '20 at 10:12