Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple files with spaces in names as single argument in bash

Tags:

bash

shell

I have tool that merges multiple files to one:

totool=""test file1.gam" "test file2.gam" "test fileN.gam""
tool $totool outfile.wrl

Problem is that tool recognise space as file delimiter and "test file1.gam" will be treated as two files. When I try do double quote variable argument:

tool "$totool" outfile.wrl

program try to open single file "test file1.gam test file2.gam test fileN.gam" instead of multiple files.

I try to escape double quotes around each file name:

totool=""\"test file1.gam\"" "\"test file2.gam\"" "\"test fileN.gam\"""

but program recognise escaped double quotes as part of file name: Unable to open file '"test file1.gam" "test file2.gam" "test fileN.gam"' for reading

Number of .gam files is variable and $totool is defined in loop.

Any suggestions?

like image 950
Ivan Avatar asked Oct 28 '25 07:10

Ivan


2 Answers

You should use an array in order to preserve arguments containing spaces, like this:

totool=( "test file1.gam" "test file2.gam" "test fileN.gam" )
tool "${totool[@]}" outfile.wrl
like image 136
dogbane Avatar answered Oct 31 '25 04:10

dogbane


Using an array is certainly reasonable. Your attempts to quote can be addressed with eval and a single quote (escaping within double quotes will work as well, but using a single quote is much cleaner):

totool='"test file1.gam" "test file2.gam" "test fileN.gam"'
eval tool $totool outfile.wrl
like image 23
William Pursell Avatar answered Oct 31 '25 03:10

William Pursell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!