嵌入式技术论坛
直播中

h1654155275.5748

7年用户 877经验值
私信 关注
[经验]

shell脚本中的#是什么意思?

最近在网上看到一个问题:

#!/bin/bash
number=10
index=20
aa=$(( 2#1 << number | index))
echo ${aa}

执行上面的shell结果是什么?

作用是什么?

首先得弄清楚#是什么意思?网上搜了一大圈没搜到,自己做几个实验看看:

[root@liabio test]# 
[root@liabio test]# echo $((2#000))
0
[root@liabio test]# echo $((2#001))
1
[root@liabio test]# echo $((2#010))
2
[root@liabio test]# echo $((2#011))
3
[root@liabio test]# echo $((2#012))
-bash: 2#012: value too great for base (error token is "2#012")
[root@liabio test]# echo $((2#100))
4
[root@liabio test]# echo $((2#101))
5
[root@liabio test]# echo $((2#102))
-bash: 2#102: value too great for base (error token is "2#102")
[root@liabio test]# echo $((2#110))
6
[root@liabio test]# echo $((2#111))
7
[root@liabio test]# echo $((2#1000))
8
[root@liabio test]# echo $((16#ff))
255
[root@liabio test]# echo $((16#1))
1
[root@liabio test]# echo $((16#16))
22
[root@liabio test]# echo $((16#15))
21
[root@liabio test]# echo $((16#10))
16
[root@liabio test]# echo $((16#9))
9
[root@liabio test]# echo $((16#a1))
161
[root@liabio test]# echo $((16#a))
10
[root@liabio test]# echo $((16#b))
11

可以看到#作用是进制转换,即a#b代表a进制的b转换为十进制。

[]和(())

它们是一样的,都是进行数学运算的。支持+ - * / %:分别为 “加、减、乘、除、取模”。但是注意,bash只能作整数运算,对于浮点数是当作字符串处理的。

运算符优先级

左移符号<<和按位或符号|优先级哪个高?

1.jpg

2.jpg

3.jpg

4.jpg

同一优先级的运算符,运算次序由结合方向所决定。

简单记就是:! > 算术运算符 > 关系运算符 > && > || >赋值运算符

结果

#!/bin/bash
number=10
index=20
aa=$(( 2#1 << number | index))
echo ${aa}

1左移10位相当于1*2^10=1024

10000000000
00000010100
------------
10000010100
------------
即10进制的2^2+2^4+2^10=1044
[root@liabio test]# cat aa.sh 
#!/bin/bash

number=10
index=20

aa=$((2#1 << number | index))
echo $aa


[root@liabio test]# sh aa.sh 
1044

原作者:小碗汤

回帖(1)

powermarch

2022-10-31 21:47:25
学习了紫薯布丁
举报

更多回帖

发帖
×
20
完善资料,
赚取积分