简体   繁体   中英

Wrong search result in a file through Bash script

I am searching an event field in a file but is giving wrong output. I am searching gpio-keys event in input devices for which I have written a script, but I'm unable to print anything in output file (in my case I am writing in a button device file it is null always). Please help me to figure out this. Where am I doing wrong in script file?

Bash script:

#!/bin/bash

  if  grep -q  "gpio-keys" /proc/bus/input/devices  ; then
    EVENT=$(cat /proc/bus/input/devices | grep "Handlers=kbd")
    foo= `echo $EVENT | awk '{for(i=1;i<=NF;i++) if($i=="evbug")printf($(i-1))}'`
    #foo=${EVENT:(-7)}
    echo -n $foo > /home/ubuntu/Setups/buttonDevice
 fi

Prakash, I don't have access to your google drive. But I just want to give you some suggestion:-

foo= `echo $EVENT | awk '{for(i=1;i<=NF;i++) if($i=="evbug")printf($(i-1))}'`

This is old style now. Better use like below:-

foo=$(echo $EVENT | awk '{for(i=1;i<=NF;i++) if($i=="evbug")printf($(i-1))}')

Also always use double quotes "" when echoing a variable. See below:-

echo -n "$foo" > /home/ubuntu/Setups/buttonDevice

Try with the below code it will work for you

#!/bin/bash

 if  grep   "gpio-keys" /proc/bus/input/devices >/dev/null ; then
    cat /proc/bus/input/devices | grep "Handlers=kbd" | awk '{for(i=1;i<=NF;i++){ if($i ~ /eve/){printf "%s \n", $i} } }') > /home/ubuntu/Setups/buttonDevice
 fi

The output in buttonDevice would be

event0
event1
.
.
.
.
event100

i am still not able to get anything in buttondevce

That's no wonder, since in the input line

H: Handlers=kbd event0

there's nowhere the evbug your awk script is looking for.

I my case it is event0 but it may vary also depends on how kernel allows.

If it is event0 or similar, then it's nonsensical to look for evbug . Change the statement

if($i=="evbug")printf($(i-1))

to

if ($i~"event") print $i

(using regular expression match).

I have rewritten my script like above. but through it, I have got two events(event0, event3) but … my input devices are many but i want the gpio-keys event

Aha - in order to take only the handler line from the gpio-keys section, you can use sed with an address range:

  EVENT=`sed -n '/gpio-keys/,/Handlers=kbd/s/.*Handlers=kbd //p' </proc/bus/input/devices`

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