我正在创建一个脚本,用于向预定义站点发出 curl 请求。不幸的是,该脚本找到了 3 个参数,但 curl 无法正常工作。
问题出在哪里?这是我的尝试。
random="$(cat something.txt)"
echo "ID: ${random} - File: $1 - Var: $2 - Cookie: $3"
url="$(curl -i -L -X POST --cookie 'info=$3' \
-F 'var=$2' \
-F 'submit=Send' \
-F 'file[]=@$1' \
https://example.com/upload?id=${random})"
第二行echo
打印出正确的值,相同的 POST 请求在直接使用参数时不会出现任何问题,但会curl
失败并出现以下错误:
Warning: setting file /my/path/to.file
Warning: failed!
答案1
哪里有问题?
您需要使用双引号。
壳牌将分析你的脚本并寻找错误:
$ shellcheck myscript
Line 1:
random="$(cat something.txt)"
^-- SC2148: Tips depend on target shell and yours is unknown. Add a shebang.
Line 3:
url="$(curl -i -L -X POST --cookie 'info=$3' \
^-- SC2034: url appears unused. Verify use (or export if used externally).
^-- SC2016: Expressions don't expand in single quotes, use double quotes for that.
Line 4:
-F 'var=$2' \
^-- SC2016: Expressions don't expand in single quotes, use double quotes for that.
Line 6:
-F 'file[]=@$1' \
^-- SC2016: Expressions don't expand in single quotes, use double quotes for that.
Line 7:
https://example.com/upload?id=${random})"
^-- SC2086: Double quote to prevent globbing and word splitting.
$