AhmFM
AhmFM

Reputation: 1782

echo 3 statements based wc -l count number returned in output

Team, I have below command that is working fine but I am enhancing it to get result like below

my goal is to report the count and display statement with it.

I have three conditions to be met

1 - if result = 0 mounts not found

2 - if result = 1-64, mounts found under 64

3 - if result = 64+, mounts found above 64

if count is 0 I want to output:

0 mounts found on this hostname

if 1-64 mounts found, then I want to say whatever number is found

x mounts found on hostname.

if anything beyond 64 mounts are found, then i want to say

x mounts found on hostname that are more than 64
mount | grep csi | grep -e /dev/sd | wc -l && echo "mounts found on $HOSTNAME" 

I am trying to learn how to compare returned count to 64 and displace statement accordingly. I need a single line shell command for all this and not a multiple coz i need to fit it in ansible shell module.

sample output:

mount | grep csi
tmpfs on /var/lib/kubelet/pods/abaa868f-2109-11ea-a1f8-ac1f6b5995dc/volumes/kubernetes.io~secret/csi-nodeplugin-token-type tmpfs (rw,relatime)
/host/dev/sdc on /var/lib/kubelet/pods/11ea-a1f8-ac1f6b5995dc/volumes/kubernetes.io~csi/ea6728b2-08d0-5fb7-b93a-5f63e49f770c/mount type iso9660 (ro,relatime,nojoliet,check=s,map=n,blocksize=2048,fsc,readahead=4096)
mount | grep csi | grep /dev/sd
/host/dev/sdc on /var/lib/kubelet/pods/11ea-a1f8-ac1f6b5995dc/volumes/kubernetes.io~csi/b93a-5f63e49f770c/mount type iso9660 (ro,relatime,nojoliet,check=s,map=n,blocksize=2048,fsc,readahead=4096)

any hint why is this not working below?

tried solution: with awk and comparison operator

mount | grep -Ec '/dev/sd.*\<csi' | awk '$0 = 0 { printf "No mounts found", $0,"TRUE" ; } ($0 > 0 && $0 <= 64)  { print "Mounts are less than 64", $0 ;} $0 > 64  { print "Mounts are more than 64", $0 ;}'

output:

node1

expected:

node1 No mounts found

Upvotes: 1

Views: 65

Answers (1)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

With extended and optimized pipeline:

mount | grep -Ec '/dev/sd.*\<csi' \
| awk '{ print $0,"mounts found on hostname"($0>64? " that are more than 64." : ".") }'

grep's -c option - suppress normal output; instead print a count of matching lines

The symbols \< and \> respectively match the empty string at the beginning and end of a word.

Upvotes: 1

Related Questions