How do I read standard out into a bash variable without using a subshell or a named pipe
Inside a bash script I am piping the output of a curl request to tee and then duplicating the output to many subshells. At 开发者_JS百科the end of each subshell I want to assign the result to a variable declared inside my script:
#!/bin/bash
token_secret=""
token_value=""
function extractTokenSecret() {
sed -n 's/.*secret":"\([^"]*\)".*/\1/p'
}
function extractTokenValue() {
sed -n 's/.*token":"\([^"]*\)".*/\1/p'
}
function createToken() {
curl -v \
-X POST \
-s http://localhost:8080/token | tee >/dev/null \
>(extractTokenSecret | [ASSIGN THE VARIABLE token_secret HERE]) \
>(extractTokenValue | [ASSING THE VARIABLE token_value HERE] \
}
Any help appreciated
The commands that consume the output of your curl command are listed after the pipe "|" character. So... they will be subshells of the current command processor, just as you say in your question. In other words, they are child processes, and cannot affect the environment of the parent shell directly.
You'll need to find some other way to process the output of the curl command that will allow your script to assign text to variables in the current shell. i.e. Don't try to do the assignment as a second or third command in a pipeline. For this, things like $() and eval(1) are your friends.
Maybe something like:
$ output=$(curl options...)
$ variable1=$(echo $output | sed ...)
$ variable2=$(echo $output | sed other stuff...)
Something along these lines should work (I haven't got a particularly clear idea of how precisely you were trying to split it up, but this should be a basis):
function createToken() {
original=`curl -v -X POST -s http://localhost:8080/token`
token_secret=`extractTokenSecret $original` # And then get extractTokenSecret to use $1
token_value=`extractTokenValue $token_secret` # Ditto
}
Also, no spaces around =
, please.
token_secret=''
token_value=''
精彩评论