使用具有不同引号级别和空格的变量构建命令字符串 [英] Building command strings using variables with various quote levels and spaces
问题描述
我有一个运行curl
的脚本.如果字符串不为空,我希望能够选择添加-H
参数.复杂的是报价和空格的水平.
I have a script that runs curl
. I want to be able to optionally add a -H
parameter, if a string isn't empty. What's complex is the levels of quoting and spaces.
caption="Test Caption"
if [ "${caption}" != "" ]; then
CAPT=-H "X-Caption: ${caption}"
fi
curl -A "$UA" -H "Content-MD5: $MD5" -H "X-SessionID: $SID" -H "X-Version: 1" $CAPT http://upload.example.com/$FN
这个想法是CAPT变量为空,或包含所需的-H标头,格式与其他标头相同,例如-H "X-Caption: Test Caption"
The idea is that the CAPT variable is either empty, or contains the desired -H header in the same form as the others, e.g., -H "X-Caption: Test Caption"
问题是在运行时,它将分配解释为要执行的命令:
The problem is when run, it interprets the assignment as a command to be executed:
$bash -x -v test.sh
+ '[' 'Test caption' '!=' '' ']'
+ CAPT=-H
+ 'X-Caption: Test caption'
./test.sh: line 273: X-Caption: Test caption: command not found
我曾尝试在代码之前重置IFS,但这并没有改变.
I've tried resetting IFS before the code, but it didn't make a difference.
推荐答案
完成这项工作的关键是使用数组.
The key to making this work is to use an array.
caption="Test Caption"
if [[ $caption ]]; then
CAPT=(-H "X-Caption: $caption")
fi
curl -A "$UA" -H "Content-MD5: $MD5" -H "X-SessionID: $SID" -H "X-Version: 1" "${CAPT[@]}" "http://upload.example.com/$FN"
这篇关于使用具有不同引号级别和空格的变量构建命令字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!