Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

linux - Minimize dependency on shell commands stdout

In my application, i am using bash scripts to gather various system information. To get the desired information i am parsing the output of shell commands. For example to get the operating mode of my wifi module i am using the following script.

iwconfig wlan0 | awk -F 'Mode:' '{ m = $2; sub(/ .*/, "", m); print m }'

The script highly depends on the output of iwconfig wlan0

wlan0     IEEE 802.11  ESSID:"Foo"
          Mode:Managed  Frequency:5.62 GHz  Access Point: 44:4E:6D:67:7A:0D   
          Bit Rate=24 Mb/s   Tx-Power=31 dBm   
          Retry short limit:7   RTS thr:off   Fragment thr:off
          Power Management:on
          Link Quality=70/70  Signal level=-28 dBm  
          Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
          Tx excessive retries:0  Invalid misc:0   Missed beacon:0

If the output of iwconfig wlan0 changes after an system update, there is a good chance that my application breaks. How is this exemplary problem handled in real world application code?

question from:https://stackoverflow.com/questions/65906118/minimize-dependency-on-shell-commands-stdout

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Ideally, find a stable API which doesn't produce human-readable output which changes between versions and perhaps between locales. On Linux, the /proc filesystem presents a stable, machine-readable representation of many aspects of system state.

For other things, modern utilities often have an option to produce JSON or other machine-readable output (in the past, XML had a similar role, but it's much less trivial to parse correctly).

If you have to code against a human-readable format like this, try to find stable, reliable test cases and run those on start-up, or perhaps less ideally in a test suite. If you can't get exactly the output you expect, something changed. Of course, your test case needs to be specific and strict enough to actually test all the aspects you care about. (For your example, maybe iwlan lo is reasonably static and predictable to work everywhere as a test case?)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...