bash - 带有空格的变量在 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 转储到一个数组并将其用作输入参数,但它仍然以同样的方式失败。
如果变量中有空格,如何将变量作为参数传递?
解决方案
如果您希望保留空格,请在双引号中嵌入变量名称。
python myscript.py -i "$imagepath"
推荐阅读
- laravel - Laravel HTTP 测试和请求属性
- java - 在java中使用PythonInterpreter导入python包
- c# - 由于无效的 Web URL,Twitter 创建应用程序失败
- postgresql - 遍历postgresql触发器中的表
- abap - 从 itab 中获取其他字段中每个不同值的最高值
- android - Android模拟器上的白屏,但屏幕截图显示它可以正常工作
- python - 用于过滤 Pandas DataFrame 行的 excel 嵌套 if 条件的 Python 等效项
- python - Python方法之间的区别是否可以创建新变量
- javascript - 使用 API 删除有时有效,有时无效
- url - QnA Maker 管理知识 - 添加新 URL 的问题