linuxbashmknod

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


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.


Solution

  • 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.