2

i wonder why i get length 1 returned every time even though $test is empty, even though grep can't find anything.

#!/bin/bash

set -Eeuo pipefail
set -x

declare -a test

test=$(echo "$outputOfOtherCommand" | grep -i '>f\+\+\+\+\+\+\+\+\+' | cut -d' ' -f2) || true
echo "${#test[@]}"

for t in $test
do
    echo $t
done

The $outputOfOtherCommand includes the output of Rsync. The test_new_file was only created for clarity.

➜  ~ ./script.sh
.d..t...... ./
>f+++++++++ test_new_file

Number of files: 10 (reg: 9, dir: 1)
Number of created files: 1 (reg: 1)
Number of deleted files: 0
Number of regular files transferred: 1
Total file size: 0 bytes
Total transferred file size: 0 bytes
Literal data: 0 bytes
Matched data: 0 bytes
File list size: 0
File list generation time: 0.001 seconds
File list transfer time: 0.000 seconds
Total bytes sent: 280
Total bytes received: 38

The only thing I can explain is that an empty entry was created at array position 0. But i don't know. Maybe you can help me.

2
  • Your for loop does not make any sense. The loop body will be executed exactly once, with t having the literal string test. Commented Feb 27, 2020 at 11:51
  • Sorry, forgot the $ when I was making the post. Commented Feb 27, 2020 at 12:55

1 Answer 1

3

test is an array only because you declared it using -a. An assignment of the form

test=$(.....) 

assigns a single string to test, which ends up in the array element with index 0. Hence the length of your array is 1.

You can verify this by

declare -a arr
arr=$(echo a b c)
echo ${arr[0]}
Sign up to request clarification or add additional context in comments.

2 Comments

I see, then my question goes in a different direction. If I remove the "declare", I can go through the "array" with a for loop. Why is this possible when there is only an array with one element at position 0?
If you remove the 'declare', test is not an array anymore, but a string, but since you did not quote $test in your loop, word splitting occurs on white space and t will take the the values of the individual words. Whether this is or is not what you want, I don't know. You need to specify, what you want the array elements to contain.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.