Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Bash word splitting in substring

Tags:

linux

bash

shell

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'
like image 547
marko Avatar asked Jun 14 '13 20:06

marko


2 Answers

Use an array:

files=( file1 'foo bar' )
ls -la "${files[@]}"
like image 128
kojiro Avatar answered Oct 02 '22 02:10

kojiro


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
like image 39
iruvar Avatar answered Oct 02 '22 02:10

iruvar