首页 > 解决方案 > 带有空格的变量在 Bash 脚本中作为参数传递

问题描述

我正在构建一个简单的脚本,它从目录中选择一个随机文件,然后将文件名作为参数传递给 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 转储到一个数组并将其用作输入参数,但它仍然以同样的方式失败。

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

标签: bashscriptingquotes

解决方案


如果您希望保留空格,请在双引号中嵌入变量名称。

python myscript.py -i "$imagepath"

推荐阅读