Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read from block special and character special devices in Linux using bash shell scripts?

Tags:

linux

bash

shell

I am trying to read from /dev/random and /dev/urandom and would like to know what is the best way to read from them and block/character special devices in general using bash shell scripting ?

like image 247
Ankur Agarwal Avatar asked Apr 26 '11 22:04

Ankur Agarwal


People also ask

How do I find special characters in Bash?

bash check if string ends with character. shell script to check whether a character is alphabet digit or special character.

How does Bash handle special characters?

Bash Character Escaping. Except within single quotes, characters with special meanings in Bash have to be escaped to preserve their literal values. In practice, this is mainly done with the escape character \ <backslash>.

Which Bash command is used to read input from keyboard?

To read the Bash user input, we use the built-in Bash command called read. It takes input from the user and assigns it to the variable.


2 Answers

Use dd to get blocks of data from the device. E.g. to get 8 bytes from /dev/urandom:

dd if=/dev/urandom count=1 bs=8 | ...

Then you can use od to convert the bytes to a human-readable form:

$ dd if=/dev/urandom count=1 bs=8 2>/dev/null | od -t x1 -A n
b4 bc 2f 59 dd 55 1b 4a

By the way, if you only need random numbers in bash, $RANDOM is probably more useful:

$ echo $RANDOM $RANDOM $RANDOM $RANDOM
3466 6521 4426 9349
like image 59
thkala Avatar answered Sep 29 '22 01:09

thkala


My hint:

dd if=/dev/urandom count=4 | ...

or e.g. The tail is heavily dependent on what you want to do with that data

To format as a long integer number:

dd if=/dev/urandom bs=1 count=4|od -l
like image 42
sehe Avatar answered Sep 29 '22 03:09

sehe