linuxbashscriptingshkey-value

Is there a standard way to grab "values" from a "key" in bash?


I'm learning bash from a book and just wanted to see if there is a more efficient way to do this.

The output of cat /proc/acpi/wakeup is multiple lines, but I only care about this one:

GPP0      S4    *disabled  pci:0000:00:01.1

So I can grep for just that line no problem, but I only need the value under the Status column, that is, I only need to know whether its value is enabled or disabled.

This part of my script is conditional. If the user tries to Suspend the system, and the status is set to disabled, it should go ahead and Suspend. Otherwise, if the status is enabled, it should disable it first before allowing the system to Suspend.

I have come up with three different approaches to this:

First approach (using cut):

cat /proc/acpi/wakeup | grep GPP0 | cut -d "*" -f 2 | cut -d " " -f 1    # 'disabled'

Second appraoch (using awk):

cat /proc/acpi/wakeup | grep GPP0 | awk '{print $3}' | cut -d "*" -f 2

Third approach:

cat /proc/acpi/wakeup | grep GPP0 | awk '{if ($3 == "*disabled") print "Already disabled"; else print "DISABLE IT"}'

I'm leaning toward the third approach, but I was wondering if there is a standard way to grab the value from the Status column. For example using GPP0 as the "key" and enabled or disabled would be the "value."

I could not find this in the manpages or tldr tool.

Also, I realize that the choice to use cat could be the problem with the script's efficiency, so if there is a better tool that is standard for grabbing values of keys, please let me know.


Solution

  • There are few standard ways to do anything in shell programming. There are almost always multiple ways to do it, with equivalent performance and maintenance cost.

    Here's a solution that is a little more concise:

    awk '$1 == "GPP0" && $3 == "*disabled" { print "Disabled" }' /proc/acpi/wakeup
    

    Awk can do many things that grep and cat can do (and other tools like cut and sed), including reading directly from a file instead of stdin.

    It's particularly awk-ish to use the pattern { action } syntax instead of using if in the action block.