-1

I have a file ~/filelist, where each line is a file's pathname, which may contain whitespaces:

/path/to/my file1
/another path/to/my file2

I have a script which can accept filenames as arguments:

myscript.sh "/path/to/my file1"  "/another path/to/my file2"

The following commands will not work however

myscript.sh $(cat ~/filelist)

and

arr=($(cat ~/filelist))
myscript.sh "${arr[@]}"

How can I make the script work with ~/filelist? Thanks.

Tim
  • 101,790

1 Answers1

3

The usual word-splitting reasons described in

For that particular case on Bash, using mapfile and the array it provides is cleanest, since you don't need to touch word splitting directly:

$ mapfile -t paths < filelist
$ myscript.sh "${paths[@]}"

Or if you want to, directly with word-splitting:

$ set -o noglob     # disable globbing, same as 'set -f'
$ IFS=$'\n'         # split only on newlines
$ myscript $(cat filelist)
ilkkachu
  • 138,973
  • Thanks. In the script there is ls -l "${@}", why does it report error ls: cannot access '"/path/to/my file1"': No such file or directory and ls: cannot access '"/another path/to/my file2"': No such file or directory? – Tim Aug 14 '18 at 22:25
  • @Tim, you have the literal quotes there, in the data? You don't need them, and they'd only be useful if you eval the command containing the filenames. – ilkkachu Aug 14 '18 at 22:41
  • Thanks. In filelist, I double quoted the pathnames which contain whitespaces – Tim Aug 15 '18 at 02:16