how to write a bash script that would get minor and major device numbers of /dev/random

2.7k Views Asked by At

I am trying to run a program in a chrooted environment, and it needs /dev/random as a resource. Manually I can do ls -l on it and then create the file again with mknod c xx yy, but I need to make it automatic and I don't think these version numbers are constant from a linux version to another so that is why I have the following question :

How could I write a bash script that would extract the minor and major numbers of /dev/random and use it with mknod? I can use ls -l but I don't know how to extract a substring of it...

The exact return of ls -l /dev/random is :

crw-rw-rw- 1 root root MINOR, MAJOR mars  30 19:15 /dev/random

and the two numbers I want to extract are MINOR and MAJOR. However if there is an easier way to create the node without ls and mknod I would appreciate it.

3

There are 3 best solutions below

12
On BEST ANSWER

You can get the major and minor device numbers with stat:

MINOR=`stat -c %T /dev/random`
MAJOR=`stat -c %t /dev/random`

You can then create a device node with:

mknod mydevice c "0x$MAJOR" "0x$MINOR"

Another approach (which doesn't require the parsing of device numbers) is to use tar to create an archive with the details of the device files in:

cd /dev
tar cf /somewhere/devicefiles.tar random null [any other needed devices]

then

cd /somewhere/chroot-location
tar xf /somewhere/devicefiles.tar

This latter method has the advantage that it doesn't rely on the -c option to stat, which is a GNU extension.

0
On

A minor improvement to efficiency would be to do only one call (and to use lower-case variable names, as is conventional for all variables other than builtins and environment variables in shell):

read minor major < <(stat -c '%T %t' /dev/random)

On a GNU system, by the way, I'd suggest using cp -a to copy your explicitly whitelisted device files into the chroot during setup:

cp -a /dev/random /your/chroot/dev/random
3
On

Try this.

MAJOR=ls -l /dev/random | awk '{ print $5}'

MINOR=ls -l /dev/random | awk '{ print $6}'