I have been working on a bash script for a few days and got stuck with filenames including single and double quotes. Give I want to iterate over the following files in a directory:
'file1.txt'
'file2.txt'
"file3.txt"
file"3.txt
file'4.txt
very 'bad file.txt
also "very bad.txt
I know that this is bad filenaming – but you know, not all people are programmers and know how to proberly name files. So I try to cope with this edge cases.
I would like to loop through the files and use them in some if statements like this for example:
dir="my/dir/"
files="$(ls -N "$dir"*)"
shopt -s extglob
for f in $files; do
if [[ "$files" = "(.png|.jpg|.jpeg|.JPG|.JPEG|*.webp)" ]]; then
for $e in "$files"; do
cp "$e" "$dir""somefilename.pdf"
else
cp "$f" "$dir""somefilename.pdf"
fi
done
Now the problem arises, that bash is intepreting the double and single quotes in the filenames and splitting up the files – errors follow…
So my question is: How to cope with these cases in bash?
mkdir ./myTestDir ; cd ./myTestDir ; touch \'file1.txt\' ; touch \"file3.txt\"
etc. – shellter Dec 20 '23 at 00:29find
instead and do-exec
things to the files, and/or have the filenames separated by null characters forxargs
to process – Xen2050 Dec 20 '23 at 08:49