How do I read standard out into a bash variable without using a subshell or a named pipe

邮差的信 提交于 2020-01-06 10:32:26

问题


Inside a bash script I am piping the output of a curl request to tee and then duplicating the output to many subshells. At 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


回答1:


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...)



回答2:


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=''


来源:https://stackoverflow.com/questions/6441868/how-do-i-read-standard-out-into-a-bash-variable-without-using-a-subshell-or-a-na

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!