简体   繁体   中英

bash: meaningful unique id generation

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM