bash: meaningful unique id generation

2.9k views Asked by At

I am using following command to generate an unique id for my shell script. I want to capture the output in a variable without using any intermediate file on hard disk.

    echo `dmidecode –t 4 -s system-uuid`-$$-$BASH_SUBSHELL-$BASHPID-`date '+%Y%m%d_%H%M_%S_%N'` | tr '-' '_'
    XXB3A1XX_81XX_4XX2_AXX4_XXXX62820BF_24115_0_8550_201709XX_1446_46_385924883

I can use backquote or $() construct but doing so changes the value of $BASH_SUBSHELL and dilutes the value of unique id.

Any solution is welcome which does not use hard disk and does not change the $BASH_SUBSHELL value while capturing the output in a variable.

note: result in the example is partly obscured with X

2

There are 2 answers

7
muru On BEST ANSWER

Use printf and save the variables in a format string:

format="%s-$$-$BASH_SUBSHELL-$BASHPID-%s"
uuid=$(printf "$format" $(dmidecode –t 4 -s system-uuid) $(date '+%Y%m%d_%H%M_%S_%N') | tr - _)

Then:

$ echo "$uuid"
XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX_11764_0_11764_20170912_1906_42_765827138
$ echo `dmidecode –t 4 -s system-uuid`-$$-$BASH_SUBSHELL-$BASHPID-`date '+%Y%m%d_%H%M_%S_%N'` | tr '-' '_'
XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX_11764_0_11865_20170912_1909_28_405748643
0
jhvaras On

There's uuidgen for Linux (util-linux) and Mac OS (BSG general commands).

See https://serverfault.com/questions/103359/how-to-create-a-uuid-in-bash