linux教程:shell脚本基本语法

2025-10-20 18:53:38

1、if判断语句的写法是这样:

#!/bin/bash

a=1;

if [ $a -lt 10 ]; then

        echo "ok"

fi

其中a=1中间一定不能有空格,如果a<10打印ok。

linux教程:shell脚本基本语法

2、保存文件。然后给文件授权:

chmod +x test.sh

然后执行脚本

./test.sh

linux教程:shell脚本基本语法

3、字符串相等:

#!/bin/bash

a="hello"

if [ $a = "hello" ]; then

        echo "ok"

fi

linux教程:shell脚本基本语法

4、字符串匹配:

注意比较条件中是[[ 条件 ]],否则会报错。例如:

#!/bin/bash

a="hello"

if [[ $a =~ "hello" ]]; then

        echo "match ok"

else

        echo "match fail"

fi

linux教程:shell脚本基本语法

5、另一种字符串比较方法:

#!/bin/bash

a="hello"

if [[ $a == *"hello"* ]]; then

        echo "match ok"

else

        echo "match fail"

fi

linux教程:shell脚本基本语法

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢