I am trying to learn shell script and writing a simple script to increment Hex values in the loop.
Here is my script:
increment=0x0001
handle=0x0001
for((i=1;i<=20;i++))
do
echo $handle
handle=$(($handle + $increment))
handle=$(printf '%x' $handle)
done
Here is my output:
0x0001
2
3
4
5
6
7
8
9
a
1
2
3
4
5
6
7
8
9
a
It is working fine till 10th iteration but after that it is starting from 1 again.
Can any one let me know my mistake?
EDIT: After removing handle=$(printf '%x' $handle) line output is:
0x0001
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Actually I want output in HEX only.
It has to do with how you print the value try printf '%#x' or printf '%#X'
Just change the line you are using to print the content with a leading 0x as:-
handle=$(printf '%#x' $handle)
(or) to have leading hex-character as 0X
handle=$(printf '%#X' $handle)
With the changes, you get the output as below:-
$ ./script.sh
0x0001
0x2
0x3
0x4
0x5
0x6
0x7
0x8
0x9
0xa
0xb
0xc
0xd
0xe
0xf
0x10
0x11
0x12
0x13
0x14
0x15
0x16
0x17
0x18
0x19
0x1a
0x1b
0x1c
0x1d
0x1e
0x1f
0x20
For more formatting options check here:- http://wiki.bash-hackers.org/commands/builtin/printf (and) http://ss64.com/bash/printf.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With