Assign AWK result to variable [duplicate]

2019-03-14 08:14发布

This question already has an answer here:

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}'

4条回答
兄弟一词,经得起流年.
2楼-- · 2019-03-14 08:44

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.

查看更多
冷血范
3楼-- · 2019-03-14 08:52

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
查看更多
唯我独甜
4楼-- · 2019-03-14 09:04

Or you can directly use:

${INDEXCOUNT##* }
查看更多
霸刀☆藐视天下
5楼-- · 2019-03-14 09:04

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

INDEXCOUNT="111 222 333"
echo $INDEXCOUNT | awk '{if ($3 == 333) print $3}';
查看更多
登录 后发表回答