How to map one array element which is separated by newlines into a new array with multiple elements

arraybashnautilusnemo

I select 4 files in Nemo in the path /home/myUsername/.local/share/nemo/scripts/Folder with spaces/. Nemo stores the file paths in the environment variable NEMO_SCRIPT_SELECTED_FILE_PATHS.

(As you can see in the answer from glenn jackman below, NEMO_SCRIPT_SELECTED_FILE_PATHS contains a newline-separated list of file paths.)

Why is "Yeah!" not printed after every file path line? How can I achieve that? (This question is maybe irritating, because I initially thought this list of file paths is an array, which it is obviously not.)

SCRIPT

#!/bin/bash

for i in "${NEMO_SCRIPT_SELECTED_FILE_PATHS[@]}"
do
    echo "$i"
    echo "Yeah!"
done

OUTPUT

/home/myUsername/.local/share/nemo/scripts/Folder with spaces/script1
/home/myUsername/.local/share/nemo/scripts/Folder with spaces/script2
/home/myUsername/.local/share/nemo/scripts/Folder with spaces/script3
/home/myUsername/.local/share/nemo/scripts/Folder with spaces/script4

Yeah!

Best Answer

Assuming:

  • the environment variable $NEMO_SCRIPT_SELECTED_FILE_PATHS is somehow magically set for you by nemo, and
  • it contains a newline-separated list of filenames,

you can parse it out into a bash array like this:

$ NEMO_SCRIPT_SELECTED_FILE_PATHS="file one
file two
file three"

$ mapfile -t files <<<"$NEMO_SCRIPT_SELECTED_FILE_PATHS"

$ echo ${#files[@]}
3

$ printf ">>%s\n" "${files[@]}"
>>file one
>>file two
>>file three

mapfile is a bash builtin command that reads standard input, splits on newlines and stores the lines in the named array.

This breaks if any of your filenames contain newlines (which is a legal filename character).

Related Question