首页 > 编程知识 正文

shell 双括号,linux 各种括号的使用

时间:2023-05-06 20:45:55 阅读:237679 作者:4661

一般我们使用如下语法

if [ expression ] thenif

linux中提供了高级的双括号语法。
在之前,如果要判断数字大小,大于号需要转义,否则会被认为重定向
举例:

[root@localhost shell]# cat test1.sh #!/atgdbm/bashnum=10if [ num > 8 ];thenecho "10>8"fi

程序解释:上面程序执行,虽然输出了10>8,但不是真正意义的比大小,而是认为了重定向,生成了文件名8。

[root@localhost shell]# ./test1.sh 10>8[root@localhost shell]# ls8 test1.sh

以上通过转义即可解决问题。

[root@localhost shell]# cat test1.sh #!/atgdbm/bashnum=10if [ num > 8 ];thenecho "10>8"fi 双括号语法 [root@localhost shell]# cat test1.sh #!/atgdbm/bashnum=10if (( $num ** 2 > 90 ));then(( result = $num ** 2 ))echo "10的平方="$resultfi[root@localhost shell]# ./test1.sh 10的平方=100

大于号不需要进行转义,写起来也简单些。

双方括号语法

双方括号里的expression使用了test命令中采用的标准字符串比较。但它提供了test命令未提供的另一个特性,模式匹配。

[root@localhost shell]# cat test1.sh #!/atgdbm/bashif [[ $USER == r* ]]thenecho "hello $USER"elseecho "Sorry,you not start with r"fi[root@localhost shell]# ./test1.sh hello root

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。