0

I have created a variable with the first 4 letters of my sample names, but when I try to pass this variable in a for loop it fails.

my_sample=$(find ~/myfolder -type f -name ".bam" | awk -F '.bam' '{print $1}' | awk -F '/normal/' '{print $2}' | sort | uniq)

I obtained this

mysample = sample1 sample2 sample3...sampleN

But when I execute this (I need to cycle using numbers and not element names)

for ((i=0;i<${#my_sample[@]};i++)); do

It considers the first iteration as the whole my_sample (i=sample1 sample2 sample3...sampleN) but I want that the first iteration is sample1, the second sample2 and so on.

If I try

a=( $my_sample )

This give me only the first name

sample1

Someone could help me please? Thanks in advance!

4
  • If you have GNU tools, you can use NUL delimiters rather than newline delimiters and this all becomes very moot. Commented Nov 29, 2023 at 15:29
  • 1
    That said -- readarray -t my_sample < <(...) Commented Nov 29, 2023 at 15:30
  • That said, a=( $my_sample ) does generate an array, even if it's buggy (and it is in fact buggy). How were you checking its contents? Use declare -p a to print an unambiguous representation of the variable. If you refer to "$a" instead of "${a[@]}", that'll only refer to the first element. Commented Nov 29, 2023 at 15:31
  • BTW, consider for i in "${!my_sample[@]}"; do -- that's not just shorter, it also works if your array has sparse indices. (Let's say you run a=( zero one two three ); unset 'a[0]' -- then the first element in array a has index 1, not 0, so unconditionally iterating starting from zero is incorrect; bash's "arrays" are really numerically-indexed maps, not what other languages call arrays). Commented Nov 29, 2023 at 15:34

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.