46

This should be pretty straightfoward and I don't know why I am struggling with it.

I am running the following psql command from within a shell script in order to find out whether all indexes have been dropped before inserting data.

INDEXCOUNT=$(psql -p $dbPort -U enterprisedb -d main_db -c "select Count(*) from all_indexes where index_schema = 'enterprisedb';")

At this point, INDEXCOUNT is equal to “COUNT ------- 0”

Now if I echo the following line I get the result I want -

echo $INDEXCOUNT | awk '{print $3}'

How do I assign the value of $INDEXCOUNT | awk ‘{print $3}’ to a variable to check it in an “IF” statement?

For example:

RETURNCOUNT=$INDEXCOUNT | awk '{print $3}'
Mat
  • 202,337
  • 40
  • 393
  • 406
user739866
  • 891
  • 1
  • 9
  • 18

4 Answers4

79

The following works correctly on bash:

 a=$(echo '111 222 33' | awk '{print $3;}' )
 echo $a # result is "33"

Another option would be to convert the string to an array:

 a="111 222 333"
 b=($a)

 echo ${b[2]}  # returns 333
nimrodm
  • 23,081
  • 7
  • 58
  • 59
1

You can try this:

RETURNCOUNT=`echo $INDEXCOUNT | awk '{print $3}'`

The idea is to include any shell command between backticks to get the result into a variable.

brandizzi
  • 26,083
  • 8
  • 103
  • 158
Mayank
  • 5,454
  • 9
  • 37
  • 60
  • `"$INDEXCOUNT"` is unlikely to be a command. – glenn jackman May 17 '11 at 14:19
  • @glenn: In that case do echo can be used... The idea is to include any shell command between backticks to get the result into a variable – Mayank May 17 '11 at 15:50
  • 2
    `$()` is preferred over `backticks` as it makes nesting commands easier – Silviu Aug 16 '12 at 09:22
  • Although this code may be help to solve the problem, providing additional context regarding _why_ and/or _how_ it answers the question would significantly improve its long-term value. Please [edit] your answer to add some explanation. – Toby Speight Jul 04 '16 at 16:33
0

This might be easier to use for testing with if statement/

INDEXCOUNT="111 222 333"
echo $INDEXCOUNT | awk '{if ($3 == 333) print $3}';
fedorqui
  • 275,237
  • 103
  • 548
  • 598
GoggiP
  • 1
0

Or you can directly use:

${INDEXCOUNT##* }
Dimitre Radoulov
  • 27,252
  • 4
  • 40
  • 48