Splitting /proc/cmdline arguments with spaces

hendry picture hendry · Jun 14, 2009 · Viewed 27.6k times · Source

Most scripts that parse /proc/cmdline break it up into words and then filter out arguments with a case statement, example:

CMDLINE="quiet union=aufs wlan=FOO"
for x in $CMDLINE
do
»···case $x in
»···»···wlan=*)
»···»···echo "${x//wlan=}"
»···»···;;
»···esac
done

The problem is when the WLAN ESSID has spaces. Users expect to set wlan='FOO BAR' (like a shell variable) and then get the unexpected result of 'FOO with the above code, since the for loop splits on spaces.

Is there a better way of parsing the /proc/cmdline from a shell script falling short of almost evaling it?

Or is there some quoting tricks? I was thinking I could perhaps ask users to entity quote spaces and decode like so: /bin/busybox httpd -d "FOO%20BAR". Or is that a bad solution?

Answer

Shriram V picture Shriram V · May 26, 2011

There are some ways:

  1. cat /proc/PID/cmdline | tr '\000' ' '

  2. cat /proc/PID/cmdline | xargs -0 echo

These will work with most cases, but will fail when arguments have spaces in them. However I do think that there would be better approaches than using /proc/PID/cmdline.