在 Bash 脚本中将空格作为参数传递的变量

Variable with Spaces Passed as Argument in Bash Script

我正在构建一个简单的脚本,它从目录中随机选择一个文件,然后将文件名作为参数传递给 Python 脚本,然后删除该文件。

#!/bin/bash

var=$(ls images/ | /usr/bin/shuf -n 1 )
imagepath="'images/"$var"'"
python myscript.py -i $imagepath
rm $imagepath

如果文件中有空格,这是故意的,脚本会失败,因为它将空格作为单个参数传递。
例如

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

如果我在 $imagepath 上的原始脚本中添加回显,然后将输出 'images my test file.jpg' 带到 rm,使用单引号,它会删除文件。它仅在脚本尝试 运行 时失败。它也适用于 python 脚本。

我已经尝试将 $imagepath 转储到数组并将其用作输入参数,但它仍然以同样的方式失败。

如果变量中有空格,我如何将其作为参数传递?

当您希望保留空格时,将变量名称嵌入双引号中。

python myscript.py -i "$imagepath"