简体   繁体   English

Shell脚本:十六进制循环

[英]Shell Script: Hexadecimal Loop

I am trying to learn shell script and writing a simple script to increment Hex values in the loop. 我正在尝试学习shell脚本并编写一个简单的脚本来增加循环中的十六进制值。

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. 它可以正常工作直到第10次迭代,但之后又从1开始。

Can any one let me know my mistake? 谁能让我知道我的错误?

EDIT: After removing handle=$(printf '%x' $handle) line output is: 编辑:删除handle=$(printf '%x' $handle)行输出为:

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' 它与如何打印值有关,请尝试使用printf '%#x'printf '%#X'

Just change the line you are using to print the content with a leading 0x as:- 只需将您要用来打印内容(以0x的行更改为:-

handle=$(printf '%#x' $handle) 

(or) to have leading hex-character as 0X (或)前导十六进制字符为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 有关更多格式选项,请参见此处:-http: //wiki.bash-hackers.org/commands/builtin/printf (和) http://ss64.com/bash/printf.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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