Reputation: 13
I'm building a simple script that picks a random file from a directory, then passes the file name as an argument to a Python Script, then deletes the file.
#!/bin/bash
var=$(ls images/ | /usr/bin/shuf -n 1 )
imagepath="'images/"$var"'"
python myscript.py -i $imagepath
rm $imagepath
If the files have spaces in them, which is the intention, the script fails because it passes the spaces as if they are single arguments.
For example
rm: cannot remove "'images/my": No such file or directory
rm: cannot remove 'test': No such file or directory
rm: cannot remove "file.jpg'": No such file or directory
If I add an echo in the original script on $imagepath, then take the output 'images my test file.jpg' to rm, with the single quotes, it deletes the file. It only fails when the script tries to run it. It also works on the python script.
I have tried dumping $imagepath to an array and using that as the input argument but it still fails in the same way.
How do I pass the variable as an argument if it has spaces in it?
Upvotes: 1
Views: 1391
Reputation: 753735
Embed variable names in double quotes when you want spaces preserved.
python myscript.py -i "$imagepath"
Upvotes: 2