提高使用循环,awk和剪切的BASH脚本的性能

Sim*_*een 0 bash awk

这是我们用于监视服务器上挂载状态的bash脚本中间的片段:

OIFS=$IFS
IFS=$'\n'
for mount in $mounts; do
        mountcount=$(($mountcount+1))
        dev=`echo $mount | awk {'print $1'};`
        dir=`echo $mount | awk {'print $2'};`
        opts=`echo $mount | awk {'print $4'};`
        state=`echo $opts | cut -d ',' -f 1`
        if [ "$state" = "ro" ]; then
                crit="true"
                break
        fi
done
IFS=$IFS
Run Code Online (Sandbox Code Playgroud)

$ mounts的内容类似于:

rootfs / rootfs rw 0 0
none /sys sysfs rw,nosuid,nodev,noexec,relatime 0 0
none /proc proc rw,nosuid,nodev,noexec,relatime 0 0
none /dev devtmpfs rw,relatime,size=1028136k,nr_inodes=218146,mode=755 0 0
none /dev/pts devpts rw,nosuid,noexec,relatime,gid=5,mode=620,ptmxmode=000 0 0
fusectl /sys/fs/fuse/connections fusectl rw,relatime 0 0
/dev/disk/by-uuid/f2337686-ec8d-429a-9002-592c564ddbf3 / ext3 rw,relatime,errors=remount-ro,barrier=0,data=ordered 0 0
none /sys/kernel/debug debugfs rw,relatime 0 0
none /sys/kernel/security securityfs rw,relatime 0 0
none /dev/shm tmpfs rw,nosuid,nodev,relatime 0 0
none /var/run tmpfs rw,nosuid,relatime,mode=755 0 0
none /var/lock tmpfs rw,nosuid,nodev,noexec,relatime 0 0
Run Code Online (Sandbox Code Playgroud)

正如您应该看到的那样,我正在解析将每一行拆分为它的组件,以查找以只读方式挂载的挂载.从功能上来说这绝对没问题,但问题是我们在100多台服务器上运行它,目前用上述数据运行上述循环需要一秒钟(有时).

我相信这个问题是由等待执行时造成的awkcut,因为它们是外部程序,所以我在想,如果有一个更有效的方法可以实现同样的功能.我不太熟悉bash,因为我知道可以帮助解决这个问题的内部功能,或者足够熟练awk地将这一切都作为一条线来完成.

我的感觉是3个呼叫awk和1个呼叫cut都可以在1行中实现awk.任何帮助非常感谢!

编辑

稍后在脚本中使用变量dev,dir和mountcount来构建输出.

编辑

我已将脚本更改为以下内容:(所有回声都在那里作为测试)

mountcount=0

OIFS=$IFS
IFS=$'\n'
for mount in $mounts; do
    mountcount=$(($mountcount+1))
    echo $mount
    echo $mount | read dev dir fs opts
    echo $dev
    echo $dir
    echo $fs
    echo $opts
    state=`echo $opts | cut -d ',' -f 1`
    if [ "$state" = "ro" ]; then
        crit="true"
        break
    fi
done
IFS=$OIFS
Run Code Online (Sandbox Code Playgroud)

这给了我以下内容:

rootfs / rootfs rw 0 0




fusectl /sys/fs/fuse/connections fusectl rw,relatime 0 0




/dev/disk/by-uuid/1be5b3ae-8239-4177-9af6-22ad0afa662a / ext3 rw,relatime,errors=remount-ro,data=ordered 0 0




/dev/disk/by-uuid/1be5b3ae-8239-4177-9af6-22ad0afa662a /dev/.static/dev ext3 rw,relatime,errors=remount-ro,data=ordered 0 0




devpts /dev/pts devpts rw,relatime 0 0




securityfs /sys/kernel/security securityfs rw,relatime 0 0
Run Code Online (Sandbox Code Playgroud)

所以read不能像预期的那样工作.

pot*_*ong 6

这可能对你有用:

OIFS=$IFS; IFS=$'\n'; ma=($mounts); IFS=$OIFS
mountcount=0
for mount in "${ma[@]}"; do
    ((mountcount++))
    fa=($mount)
    dev=${fa[0]}
    dir=${fa[1]}
    opts=${fa[3]}
    state=${fa[3]/,*}
    if [ "$state" = "ro" ]; then
            crit="true"
            break
    fi
done
Run Code Online (Sandbox Code Playgroud)