bash - 可选地在 bash 脚本中传递参数
问题描述
我想在使用 rsync 时使用自定义身份文件,但前提是该文件存在,否则我不想为 rsync 使用自定义 ssh 命令。我遇到了引号问题。请参阅示例。
身份文件存在时所需的命令
rsync -e "ssh -i '/tmp/id_rsa'" /tmp/dir/ u@h:/tmp/dir
身份文件不存在时所需的命令
rsync /tmp/dir/ u@h:/tmp/dir
我想创建一个包含-e "ssh -i '/tmp/id_rsa'"
和使用它的变量,如下所示
rsync ${identityArg} /tmp/dir/ u@h:/tmp/dir
此变量可以为空或包含所需的 ssh 命令。
我填充变量的示例方法(我尝试了很多方法)
IDENTITY_FILE="/tmp/id_rsa"
if [ -f "${IDENTITY_FILE}" ]; then
identityArg="-e 'ssh -i \"${IDENTITY_FILE}\"'"
fi
问题是命令中的引号总是错误的,我最终得到与这些类似的命令(set -x
在脚本中设置,这是输出)
rsync -e '\ssh' -i '"/tmp/id_rsa"'\''' /tmp/dir/ u@h:/tmp/dir
关于 bash 中的引用,我没有得到一些东西。如果您有任何关于在 bash 脚本中使用单引号和双引号的好资源,我想阅读它。
解决方案
您要添加两个位置参数:-e
和ssh -i '/tmp/id_rsa'
,其中/tmp/id_rsa
是扩展变量。您应该为此使用数组:
args=(/tmp/dir/ u@h:/tmp/dir)
idfile=/tmp/id_rsa
# Let [[ ... ]] do the quoting
if [[ -f $idfile ]]; then
# Prepend two parameters to args array
args=(-e "ssh -i '$idfile'" "${args[@]}")
fi
rsync "${args[@]}"
我不相信内部单引号对于 是必要的ssh -i
,但这会扩展到问题中显示的命令。
推荐阅读
- reactjs - 根据数据列表选项重定向到其他页面(Reactjs)
- javascript - 获取可编辑 div 中选定元素的 id
- mysql - Laravel:查询生成器生成器返回与实际 mysql 查询不同的结果
- python - 如何创建用于检查句子相似性的矩阵模板?
- rest - 将参数包含在 GET 请求的正文而不是 URI 中是 RESTful 吗?
- python - Python 3.7 \n not working in variable List[] but works for tuple() and string "" varaibles? confused
- ios - 如何在 UITableView 单元格中创建自定尺寸网格?
- qt - 在创建 QApplication 对象之前创建一个 QStatemachine 对象可以吗?
- android - Raw body request with retrofit
- python - 大熊猫在奇数行取平均值