Linux 循环控制语句及状态返回值:break、continue、exit、return

循环控制语句

  1. break:跳出当前循环,跳出后不再执行循环语句。

  2. continue:跳过当前循环,继续执行下一次循环。

状态返回值

  1. exit:退出当前 shell 或者程序,返回状态值。

  2. return:退出函数,返回状态值。只能在函数中使用,不能在 shell 中使用。

示例

  1. break 语句
#!/bin/bash
for i in {1..5}
do
    if [ $i -eq 3 ]
    then
        break
    fi
    echo $i
done

输出:

1
2
  1. continue 语句
#!/bin/bash
for i in {1..5}
do
    if [ $i -eq 3 ]
    then
        continue
    fi
    echo $i
done

输出:

1
2
4
5
  1. exit 语句
#!/bin/bash
echo 'hello world'
exit 1

输出:

hello world
  1. return 语句
#!/bin/bash
function myfunction()
{
    echo 'hello world'
    return 1
}
myfunction
echo $?

输出:

hello world
1
Linux 循环控制语句及状态返回值:break、continue、exit、return

原文地址: https://www.cveoy.top/t/topic/nCzr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录