I have a command
for i in {1..9} ; do cansend slcan0 "7e0#02090"$i"0000000000"
How can I send the same command but for $i send 4 bytes of HEX instead. Sort of like a brute force ?
I have a command
for i in {1..9} ; do cansend slcan0 "7e0#02090"$i"0000000000"
How can I send the same command but for $i send 4 bytes of HEX instead. Sort of like a brute force ?
You can use the printf
utility and %04x
as a format specifier (0
pad, 4
characters, format as hex
):
for i in {1..9}; do
command=$(printf "7e0#02090%04x0000000000" $i)
echo cansend slcan0 "$command" # remove `echo` here :)
done
prints out
cansend slcan0 7e0#0209000010000000000
cansend slcan0 7e0#0209000020000000000
cansend slcan0 7e0#0209000030000000000
cansend slcan0 7e0#0209000040000000000
cansend slcan0 7e0#0209000050000000000
cansend slcan0 7e0#0209000060000000000
cansend slcan0 7e0#0209000070000000000
cansend slcan0 7e0#0209000080000000000
cansend slcan0 7e0#0209000090000000000
You could use brace expansion to generate a list of all 4-byte hex code sequences (00000000
, 00000001
, 00000002
, …, FFFFFFFF
).
{{0..9},{A..F}}
generates the list 0 1 2 … F
.
{{0..9},{A..F}}{{0..9},{A..F}}
generates the list 00 0 02 … FF
.
And so on.
For 4 bytes you have to repeat {{0..9},{A..F}}
8 times as every byte has two hex digits.
for i in {{0..9},{A..F}}{{0..9},{A..F}}{{0..9},{A..F}}{{0..9},{A..F}}{{0..9},{A..F}}{{0..9},{A..F}}{{0..9},{A..F}}{{0..9},{A..F}}; do
cansend slcan0 "7e0#02090${i}0000000000"
done
While this approach might be viable for two or three digits I would strongly advise against using it in this case. Above script is not readable and very slow.
The next better thing in bash would be …
bytes=4
((max=2**(bytes*8)-1))
for ((i=0; i<max; i++)); do
printf -v hex %08x "$i"
cansend slcan0 "7e0#02090${hex}0000000000"
done
… but please keep in mind that this will be magnitudes slower than sending sequences from a (for instance) python program which doesn't have to start a new process each time you want to send something to slccan0.