Prepending a variable to all items in a bash array

2020-04-19 06:12发布

问题:

CURRENTFILENAMES=( "$(ls $LOC -AFl | sed "1 d" |  grep "[^/]$" | awk '{ print $9 }')" )

I have written the above code, however it is not behaving as I expect it to in a for-loop, which I wrote as so

  for a in "$CURRENTFILENAMES"; do
      CURRENTFILEPATHS=( "${LOC}/${a}" )
  done

Which I expected to prepend the value in the variable LOC to all of the items in the CURRENTFILENAMES array, however it has just prepended it to the beginning of the array, how can I remedy this?

回答1:

You need to use += operator for appending into an array:

CURRENTFILEPATHS+=( "${LOC}/${a}" )

However parsing ls output is not advisable, use find instead.


EDIT: Proper way to run this loop:

CURRENTFILEPATHS=()
while IFS= read -d '' -r f; do
   CURRENTFILEPATHS+=( "$f" )
done < <(find "$LOC" -maxdepth 1 -type f -print0)


标签: arrays bash