1

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?

2
  • Why not parse ls? Commented May 17, 2020 at 4:38
  • Don't try to embed shell syntax (quotes, escapes, etc) in your data (e.g. variables' values); it doesn't work. Instead put double-quotes around variable references (e.g. "$imagepath" instead of just $imagepath). See this question. Commented May 17, 2020 at 7:54

1 Answer 1

2

Embed variable names in double quotes when you want spaces preserved.

python myscript.py -i "$imagepath"
Sign up to request clarification or add additional context in comments.

1 Comment

This worked, with a little clean up on the original script.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.