I have a problem, with this simple script (pick a random file):
#!/usr/bin/env bash
set -x
srcDir="/home/user/Desktop/wallPapers/{dir1,dir2,dir3}"
randomFile=$(find "$srcDir" -type f -iname "*.jpg" | shuf -n 1)
printf '[%s]\n' $randomFile
set +x
The problem is that while I can type this at the command line (and works perfectly fine):
find /home/user/Desktop/wallPapers/{dir1,dir2,dir3} -type f -iname "*.jpg"
Then the bash debugging set-commands (set -x and +x) tells me, that for some reason bash both encloses the directory string with single quotation marks and it also replaces the double quotation marks with single quotation marks?
./script.sh
+ srcDir='/home/user/Desktop/wallPapers/{dir1,dir2,dir3}'
++ find '/home/user/Desktop/wallPapers/{dir1,dir2,dir3}' -type f -iname '"*.jpg"'
find: ‘/home/user/Desktop/wallPapers/{dir1,dir2,dir3}’: No such file or directory
+ randomFile=
+ printf '[%s]\n'
[]
+ set +x
I understand, this is what bash sees, when the script runs:
find '/home/user/Desktop/wallPapers/{dir1,dir2,dir3}' -type -iname '*.jpg'
And this causes the "No such file or directory"-message, very very annoying... I do not understand, why it inserts these single quotation marks, I want double quotation marks used instead, just like on the command line... Could anyone please explain, I would be happy for that, thanks!
"*.jpg"
that doesn't happen, it's{dir1,dir2,dir3}
.*.jpg
, infind . -iname '*.jpg'
, is parsed byfind
, not by bash; it's expected that it not be expanded by the shell -- if it were,find
would never see it. Thus, having a single layer of syntactic quotes (and no literal quotes) is entirely correct and desired in that case. ("Literal" quotes are quotes that are part of the data, and thus passed tofind
; "syntactic" quotes are quotes that are part of the shell syntax, and thus consumed by bash itself).