Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bash Script: result of xargs assigned to variable loses all but one item

I’m running a bash script that greps through files to identify tests, then it should output the results to a string and store in a variable. When the command is run on its own it echoes out all the files in a single line correctly, but when I try to assign the results to a variable, only one is shown.

This works as expected and will show a complete list of the files expected.

grep -Erli ' @IsTest| testmethod' './build/source/classes' | sed 's#.*/## ; s#.cls##' | xargs echo

However, when I do this the result of the echo is that only one file is listed in the TESTS variable

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

TESTS=($(grep -Erli ' @IsTest| testmethod' './build/source/classes' | sed 's#.*/## ; s#.cls##' | xargs echo))
echo $TESTS

Is there something about putting this in a variable assignment expression that is a problem? It seems to be an issue of the whitespace between each item. If I add | tr ' ' ',' to the end so it replaces whitespace with commas everything is listed, but that’s not a solution I can use for this. I need a whitespace separated list of files.

>Solution :

TESTS=( ... ) is creating an array of entries.

echo $TESTS is the same as echo ${TESTS[0]}, ie, display the 1st entry in the array.

To display the entire contents of the array try echo "${TESTS[@]}" or typeset -p TESTS.

Consider:

$ TESTS=( a b c )

$ echo "$TESTS"
a

$ echo "${TESTS[0]}"
a

$ echo "${TESTS[@]}"
a b c

$ typeset -p TESTS
declare -a TESTS=([0]="a" [1]="b" [2]="c")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading