Bash – Passing Arguments from a File to a Bash Script

bashscriptingshell-script

I've got this situation:

./
./myscript.sh
./arguments.txt
./test.sh

Inside myscript.sh, I have to run the file test.sh, passing to it the arguments contained inside arguments.txt.

myscript.sh is:

arguments=$(cat arguments.txt)
source test.sh $arguments

This works well if if arguments.txt contains at most one argument:

firstargument 

The substitution is:

++ source test.sh 'firstargument'

But the problem is with two or more arguments. It does this:

++ source test.sh 'firstargument secondargument'

Also, I don't know in advance the number of arguments inside arguments.txt. There can be zero or more.

Best Answer

Assuming each line of arguments.txt represents a separate argument, with bash 4 you can read arguments.txt into an array using mapfile (each line from the file goes in as an array element, in sequence) and then pass the array to the command

mapfile -t <arguments.txt
source test.sh "${MAPFILE[@]}"

The advantage is that splitting on spaces embedded inside lines is avoided

With lower versions of bash

IFS=$'\n' read -ra arr -d '' <arguments.txt
source test.sh "${arr[@]}"
Related Question