user1559625
user1559625

Reputation: 2673

Meaning of this shell script line with awk

I read this line of script in book [linux device drivers]. What does it do?

major=$(awk "\\$2=  =\"$module\" {print \\$1}" /proc/devices)

as in context:

#!/bin/sh
module="scull"   
device="scull"  
mode="664"

# invoke insmod with all arguments we got  
# and use a pathname, as newer modutils don't look in . by default

/sbin/insmod ./$module.ko $* || exit 1


# remove stale nodes  
rm -f /dev/${device}[0-3]   

major=$(awk "\\$2=  =\"$module\" {print \\$1}" /proc/devices)

mknod /dev/${device}0 c $major 0
....

Upvotes: 6

Views: 1692

Answers (3)

Guru
Guru

Reputation: 17014

A better way to write this would be :

major=$(awk -v mod=$module '$2==mod{print $1}' /proc/devices)

Upvotes: 8

cmbuckley
cmbuckley

Reputation: 42517

/proc/devices contains the currently configured character and block devices for each module.

Expanding a few variables in your context, and fixing the syntax error in the equality, the command looks like this:

awk '$2=="scull" {print $1}' /proc/devices

This means "if the value of the second column is scull, then output the first column."

This command is run in a subshell — $(...) — and the output is assigned to the variable $major.

The explanation of the purpose is in the book:

The script to load a module that has been assigned a dynamic number can, therefore, be written using a tool such as awk to retrieve information from /proc/devices in order to create the files in /dev.

Note that in the distributed examples, the line in scull_load matches Vivek's correction.

Upvotes: 1

Vivek
Vivek

Reputation: 2020

I read this too but that line was not working for me. I had to modify it to

major=$(awk "\$2 == \"$module\" {print \$1}" /proc/devices)

The first part \$2 == \"$module\" is the pattern. When this is satisfied, that is, the second column is equal to "scull", the command print \$1 is executed which prints the first column. This value is stored in the variable major. The $ needs to be escaped as they need to be passed as it is to awk.

Upvotes: 2

Related Questions