如何在bash中的curl命令中设置变量?

Val*_*kyi 18 command-line scripts curl

我有一个 bash 文件:

#!/bin/bash

# yesnobox.sh - An inputbox demon shell script
OUTPUT="/tmp/input.txt"

# create empty file
>$OUTPUT

# cleanup  - add a trap that will remove $OUTPUT
# if any of the signals - SIGHUP SIGINT SIGTERM it received.
trap "rm $OUTPUT; exit" SIGHUP SIGINT SIGTERM

# show an inputbox
dialog --title "Inputbox" \
--backtitle "Search vacancies" \
--inputbox "Enter your query " 8 60 2>$OUTPUT

# get respose
respose=$?

# get data stored in $OUPUT using input redirection
name=$(<$OUTPUT)

curl -d '{"query":"developer", "turnOff":true}' -H "Content-Type: application/json" -X POST http://localhost:8080/explorer
Run Code Online (Sandbox Code Playgroud)

在最后一个字符串(curl命令)中,我想设置变量名称而不是"developer"。如何正确插入?

Byt*_*der 26

要访问变量,您必须在名称前放置一个美元符号: $name

但是,变量不会在用“单引号”括起来的字符串内扩展。但是,您应该将它们包含在“双引号”中,以防止扩展值(如果它可能包含空格)的分词。

所以基本上有两种方法,我们要么将整个参数放在双引号中以使变量可扩展,但随后我们必须对里面的双引号字符进行转义,以便它们最终出现在实际参数中(命令行缩短):

curl -d "{\"query\":\"$name\", \"turnOff\":true}" ...
Run Code Online (Sandbox Code Playgroud)

或者,我们可以通过将它们紧挨着编写来连接包含在不同引号类型中的字符串文字:

curl -d '{"query":"'"$name"'", \"turnOff\":true}' ...
Run Code Online (Sandbox Code Playgroud)


mgo*_*gor 9

由于 curls-d参数的值在单引号内意味着不会有参数扩展,因此仅添加变量是行不通的。您可以通过结束字符串文字、添加变量然后再次启动字符串文字来解决此问题:

curl -d '{"query":"'"$name"'", "turnOff":true}' -H "Content-Type: application/json" -X POST http://localhost:8080/explorer
Run Code Online (Sandbox Code Playgroud)

变量周围的额外双引号用于防止不需要的 shell 参数扩展。


che*_*ner 6

@ByteCommander 的回答很好,假设您知道 的值name是正确转义的 JSON 字符串文字。如果您不能(或不想)做出这种假设,请使用类似jq为您生成 JSON的工具。

curl -d "$(jq -n --arg n "$name" '{query: $n, turnOff: true}')" \
     -H "Content-Type: application/json" -X POST http://localhost:8080/explorer
Run Code Online (Sandbox Code Playgroud)


Den*_*son 6

有些人可能会发现这更具可读性和可维护性,因为它避免了使用转义以及单引号和双引号序列,这些都很难跟踪和匹配。

使用 Bash 的等效sprintf于模板替换:

printf -v data '{"query":"%s", "turnOff":true}' "developer"

curl -d "$data" -H "Content-Type: application/json" -X POST http://localhost:8080/explorer
Run Code Online (Sandbox Code Playgroud)