sh scripting question

Polytropon freebsd at edvax.de
Fri Oct 16 13:01:57 UTC 2020


On Thu, 15 Oct 2020 20:40:04 -0400, Robert Huff wrote:
> 
> 	I have a file ("files.list") with a list of filenames, similar to
> 
> 	/path A/path B/FreeBSD is great.txt
> 
> 	(note the embedded spaces)
> 	If I use
> 
> 	for FILE in `cat files.list`
> 
> 	FILE will be set to "/path".
> 	How do I get it to read the entire string?
> 	Or am I using the wrong tool?

Generally speaking, you need to set IFS, the input field
separator, to newline instead of space. You also have to
pay attention to every point during the script you will
use ${FILE}.

For example:

OLD_IFS=$IFS
IFS="
"
for FILE in `cat files.list`; do

	something ... "${FILE}"

done
IFS=$OLD_IFS

Instead of a literal linebreak, you could probably also use
something more elegant like IFS=`printf "\n"`. Also note the
quotes around each use of ${FILE}.



But:

Whenever this comes up - spaces in filenames -, I tend to
suggest _first_ reading the following two articles:

Filenames and Pathnames in Shell: How to do it Correctly
David A. Wheeler
2020-02-22 (original version 2010-05-19)

https://dwheeler.com/essays/filenames-in-shell.html

And:

Fixing Unix/Linux/POSIX Filenames:
Control Characters (such as Newline), Leading Dashes, and Other Problems
David A. Wheeler
2019-03-18 (originally 2009-03-24)

https://dwheeler.com/essays/fixing-unix-linux-filenames.html

There is so much wisdom and knowledge in those articles,
you won't regret reading them, thinking about them, and
finally understanding the problem space you've entered. :-)

You can easily use sh for processing such filenames if you
take care for a few important things. Especially if you do
not have the option to "normalize" the names, i. e., replace
spaces with underscores (the common replacement character),
there is a way you can go.




-- 
Polytropon
Magdeburg, Germany
Happy FreeBSD user since 4.0
Andra moi ennepe, Mousa, ...


More information about the freebsd-questions mailing list