marko
marko

Reputation: 642

Prevent Bash word splitting in substring

How can I prevent Bash from splitting words within a substring? Here's a somewhat contrived example to illustrate the problem:

touch file1 'foo bar'
FILES="file1 'foo bar'"
ls -la $FILES

Is it possible to get 'foo bar' regarded as a single string by the ls command within $FILES that would effectively result in the same behavior as the following command?

ls -la file1 'foo bar'

Upvotes: 9

Views: 3601

Answers (2)

iruvar
iruvar

Reputation: 23374

kojiro's array solution is the best option here. Just to present another option you could store your list of files in FILES with a different field separator than whitespace and set IFS to that field separator

OLDIFS=$IFS
FILES="file1:foo bar"
IFS=':'; ls -la $FILES
IFS=$OLDIFS

Upvotes: 2

kojiro
kojiro

Reputation: 77137

Use an array:

files=( file1 'foo bar' )
ls -la "${files[@]}"

Upvotes: 16

Related Questions