user567
user567

Reputation: 3842

Use variable as command line input in shell script

I execute this command in my shell script.

sudo hcitool -i hci0 cmd 0x08 0x0008 1e 02 01 1a 1a ff 4c 00 02 15 e2 c5 6d b5 df fb 66 j8 hj g7 d0 f5 a7 10 96 e0 99 99 99 99 c5 00

I want to change the 4 couples of 99 to the same random value I generated,I tried this code but I gut 00. The random function is working fine.

random="$(cat /dev/urandom | base64 | head -c 2)"
echo $random
sudo hcitool -i hci0 cmd 0x08 0x0008 1e 02 01 1a 1a ff 4c 00 02 15 e2 c5 6d b5 df fb 66 j8 hj g7 d0 f5 a7 10 96 e0 $random $random $random $random c5 00

Upvotes: 2

Views: 89

Answers (2)

user1934428
user1934428

Reputation: 22225

How about

random=$(printf "%02x\n" $((RANDOM % 256))) # zsh and bash

?

BTW, if you do not need a leading zero for hex numbers less than 10, and if it is OK to use Zsh instead of bash, you can also do in the following way, which doesn't need a $(...) subprocess:

random=$(( [##16] (RANDOM & 16#FF) )) # zsh only

Upvotes: 0

janos
janos

Reputation: 124648

The problem is most probably that cat /dev/urandom | base64 | head -c 2 doesn't generate a hexadecimal number. Try this way instead:

random=$(cat /dev/urandom | head -c 1 | xxd -p)

And instead of using cat and head, it would be simpler and cleaner using just xxd (thanks @kojiro for the tip!):

random=$(xxd -p -l1 < /dev/urandom)

Upvotes: 3

Related Questions