Search code examples
arraysbashenvironment

Sharing a list of files containing spaces in multiple scripts


I have a list of a number of filenames (containing spaces) which I want to use in multiple scripts.

script1:
myprog.py my favourite files

script2:
for f in my favourite files

I have tried using an environment variable but that fails due to the spaces. How can I do this?


Solution

  • Let's assume a file that has your list in it.

    $: cat lst
    this file.txt
    my favorite.csv
    that other.mpg
    

    For simplicity, here's my version of one of your programs.

    $: cat script1
    for f in "$@"; do echo "$f"; done
    

    So if I understand you correctly, you are calling it this way, and getting this sort of wrong result:

    $: ./script1 this file.txt my favorite.csv that other.mpg
    this
    file.txt
    my
    favorite.csv
    that
    other.mpg
    

    First, read up on proper quoting.

    $: ./script1 "this file.txt" "my favorite.csv" "that other.mpg"
    this file.txt
    my favorite.csv
    that other.mpg
    

    and try using arrays.

    $: mapfile -t ary < ./lst
    $: ./script1 "${ary[@]}"
    this file.txt
    my favorite.csv
    that other.mpg
    

    This works inside the script too. Try just passing name of the file that has the list, and let your program read it.