Raunak
Raunak

Reputation: 6507

Convert output into key=value pair

I have a script (I don't have edit access) which output whether the server is up or not. Essentially outputting either true or false.

How can I convert that output from lets say true to a key value pair like server_up=true or server_up=false. I tried using awk '{print $0} but didn't get very far. Not really sure how I can prepend string before it.

Thanks for any insights team!

Upvotes: 0

Views: 578

Answers (3)

Jetchisel
Jetchisel

Reputation: 7801

Using the builtin read command with ProcSub

#!/usr/bin/env bash

read -r value < <(script_that_generates_the_output)

server_up=$value

To answer this:

How can I convert that output from lets say true to a key value pair like server_up=true or server_up=false.

#!/usr/bin/env bash

read -r value < <(script_that_generates_the_output)

case "$value" in
  true) server_up=true;;
  false) server_up=false;;
esac

The case statement is most probably superfluous though.

Upvotes: 0

KamilCuk
KamilCuk

Reputation: 141200

Just output the variable with = in front of it then.

printf server_up=
prog.sh your args

Upvotes: 0

Paul Hodges
Paul Hodges

Reputation: 15313

If the output is only true or false, for one server, you can assign it directly to a variable.

server_up=$( prog.sh some arg list )

If you need that as a k=v pair,

printf "server_up=%s\n" $( prog.sh some arg list )

Obviously you have to run the program itself to get the output, but there's no need for an awk.

If you just want to use awk,

prog.sh your args | awk '{ print "server_up="$0 }'

or sed,

prog.sh your args | sed 's/^/server_up=/'

if there might be spaces to clean up, then

prog.sh your args | sed 's/^ */server_up=/'

or

prog.sh your args | sed -E 's/^\s*(\S+)\s*$/server_up=\1/'

Upvotes: 2

Related Questions