简体   繁体   中英

inline if else statement in bash

I run the below code

iostat -x 1 2 | sed 's/,/./g' | awk '/^avg-cpu/        {c++; a=2} 
                c==2 && a && !--a {printf ("%s,%s,%s,", $1, $3, $4)} 
                c==2 && /^sda/    {printf ("%s,", $14)}
                c==2 && /^sdb/    {printf ("%s,", $14)}
                c==2 && /^nvme0n1/    {printf ("%s,",$14)}'

in order to get the values of cpu and disk i/o. What I'm now trying to do is a check if there is nvm disk or not. If there is print its util otherwise print -1.00.

I tried

if [ c==2 && /^nvme0n1/ ] then {printf ("%s,",$14)}; else {printf -1.00}'

and I'm getting

awk: cmd. line:5:                        if [ c==2 && /^nvme0n1/ ] then {printf ("%s,",$14)}; else {printf -1}
awk: cmd. line:5:                        ^ syntax error
awk: cmd. line:5:                        if [ c==2 && /^nvme0n1/ ] then {printf ("%s,",$14)}; else {printf -1}
awk: cmd. line:5:                                                ^ syntax error
awk: cmd. line:5:                        if [ c==2 && /^nvme0n1/ ] then {printf ("%s,",$14)}; else {printf -1}
awk: cmd. line:5:                                                                             ^ syntax error

and

c==2 && !/^nvme0n1/ {printf ("%s,",1.00)}'

which gives me more than one 1.00, I guess each 1.00 for each time cannot find it.

Unfortunately, I got no help from ShellCheck 在此处输入图片说明

It sounds like you're trying to get the disk throughput utilization or -1 is not available with awk .

awk is its own, separate scripting language, and you can't use any bash syntax in it.

The main issue, though, is that there is no way to determine whether or not you've found your number until you've read all lines. Once you've processed all the lines, you can determine whether to print a number or -1 . You can use awk's special END block for that. This code additionally uses the special BEGIN block to set the default value:

iostat -x 1 2 | sed 's/,/./g' | awk '
            BEGIN {
              disk = -1;
            }
            /^avg-cpu/        {c++; a=2}
            c==2 && a && !--a {printf ("%s,%s,%s,", $1, $3, $4)}
            c==2 && /^sda/    { disk=$14;}
            c==2 && /^sdb/    { disk=$14; }
            c==2 && /^nvme0n1/    { disk=$14; }
            END {
              printf("%s", disk);
            }
        '

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM