skip to Main Content

I am calling python command which will return data is JSON key-value pair.

I have put python command and other command in one shell script named as – a.sh

Code (a.sh):

cd /home/drg/Code/dth

a=$(python3 main.py -z shell -y droub -i 56)

echo "$a"

When I am calling this script I am getting output as:

{'password': 'XYZ', 'name': 'Stguy', 'port': '5412', 'host': 'igtet', 'db_name': 'test3'}

And after getting this output I want to pass the output value like password, name to psql command to run postgresql query.

So, what I want is that I should be able to store password value in one variable, name in one variable like:

a= xyz
b=Stguy
p= port

So, that I can use this variables to pass in psql query as:

psql -h $a -p $p -U $b -d $db -c "CREATE SCHEMA IF NOT EXISTS  ${sname,,};"

Can someone please help me with this?

Note: Env is linux(Centos 8)

Thanks in advance!

2

Answers


  1. One way of solving this could be a combination of jq for value extraction and shell-builtin read for multiple variable assignment:

    JSON='{"name": "Stguy", "port": 5412, "host": "igtet", "db_name": "test3"}'
    read -r a b c <<<$( echo $JSON | jq -r '"(.host) (.port) (.name)"' )
    echo "a: $a, b: $b, c: $c"
    
    • doing jq string interpolation "( )" to print result in one line
    Login or Signup to reply.
  2. You can aslo go with sed or awk:

    PSQL="$( python3 main.py -z shell -y droub -i 56 | sed "s/^[^:]*: *'([^']*)'[^:]*: *'([^']*)'[^:]*: *'([^']*)'[^:]*: *'([^']*)'[^:]*: *'([^']*)'}/psql -h '4' -p '1' -U '2' -d '5'/")"
    [ "${PSQL:0:5}" = "psql " ] && ${PSQL} -c "CREATE SCHEMA IF NOT EXISTS  ${sname,,};"
    

    For security consideration, i urge you anyway to avoid passing account data (user passwd) through environment variables.

    It would be better if your python script had an option to directly launch psql with required parameters.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search