noober
noober

Reputation: 1505

How to substitute variables correctly within a function

I'm having difficulty getting the correct variable substitution to work within this function, especially the use of echo "$(...) string.

outputOFF ()
{
   host='mydevreporting.com'
   _pw='123456foobar'
   _dt=$(date +'%m-%d-%y')
   exp="SELECT * FROM metrics.account_use where account='foo' and profile='bar' order by date desc;";
   echo "$(grep real < <({ time mysql -u admin -p${_pw} -h ${host} -N -e "$exp"} 2>&1)):localhost:${_dt}"
   #echo "$(grep real < <(\{ time mysql -u admin -p${_pw} -h ${host} -N -e "$exp"\} 2>&1)):localhost:${_dt}"
}

From the command line, it will work:

echo "$(grep real < <({ time mysql -u admin -p123456foobar -h mydevreporting.com -N -e "SELECT * FROM metrics.account_use where account='foo' and profile='bar' order by date desc;"; } 2>&1)):localhost:$(date +'%m-%d-%y')" 

As I'm seeing error messages:

./tst.sh: command substitution: line 40: syntax error near unexpected token `)'
./tst.sh: command substitution: line 40: `{ time mysql -u admin -p${_pw} -h ${host} -N -e "$exp"} 2>&1)'

As you can see the echo "$(...) is inside this function outputOFF().

I've also tried escaping the braces \{, \}, which allows the variables to substitute, but somehow that command isn't working as it should. echo "$(grep real < <(\{ time mysql -u admin -p${_pw} -h ${host} -N -e "$exp"\} 2>&1)):localhost:${_dt}"

So, i'm stuck.

Upvotes: 0

Views: 65

Answers (2)

ULick
ULick

Reputation: 999

Less braces makes it more readable, at least for me.

result=$( { time mysql -u admin -p${_pw} -h ${host} -N -e "$exp"; } 2>&1 | grep real  ); 
echo "${result}:localhost:${_dt}"

time is reporting on stderr. Thus the {} are neceessary to capture the output.

Or discarding the result, and only capture the result of time.

result=$( { time mysql -u admin -p${_pw} -h ${host} -N -e "$exp" >/dev/null; }  2>&1 )
echo ${result}":localhost:${_dt}"

The unquoted ${result} is printed without the newlines. Thus you can keep all information from time with the additional timestamp.

Upvotes: 1

codeforester
codeforester

Reputation: 42999

You are missing a ; in the {...} group expression, after "$exp" (see this documentation for why). Here is the corrected version:

echo "$(grep real < <({ time mysql -u admin -p${_pw} -h ${host} -N -e "$exp"; } 2>&1)):localhost:${_dt}"

Upvotes: 2

Related Questions