noober
noober

Reputation: 1505

bash scripting - how to use results from a function that is called as a variable

Trying to figure out how to pass results of one function to another (as a variable). Below is the script I am working on:

#!/usr/local/bin/bash

set -x
_creds=/path/access
_pgpw=$(getPW)

getPW(){ 
  masterpw=$(grep -E 'url.*myfooapp.com' -A4 ${_creds}/access.json \
  | grep "pwd" \
  | awk '{split($0,a,":"); print a[2]}' \
  | grep -o '".*"' \
  | tr -d '"')
}

runQuery(){
  PGPASSWORD="${_pgpw}" \
  psql -h myfooapp.com -U masteruser -d dev -p 5439 
  echo "CLUSTER: ${_cluster}"
}

runQuery
set -x

What I need is PGPASSWORD to get the results from function getPW and its returning empty. I'm not sure if I did this correctly with the variable _pgpw=$(getPW) with trying to call a function. Please advise on best way to accomplish this. Thanks

Upvotes: 0

Views: 73

Answers (2)

Grisha Levit
Grisha Levit

Reputation: 8617

Bash executes a script line by line as it reads it. You need to define the function first, then call it. As your script is written, getPW is called before it is defined so it is not producing any output. Just move the _pgpw=$(getPW) line below the getPW() definition.

Upvotes: 1

chepner
chepner

Reputation: 530853

Functions can take arguments; they are accessed inside the function via the positional parameters $1, $2, etc.

runQuery () {
    PGPASSWORD=$1
    psql ...
}

runQuery "$(getPW)"

Upvotes: 1

Related Questions