Shell脚本中&&和||语法解析

https://www.cnblogs.com/liuyuelinfighting/p/16377705.html

在 Shell 脚本中,&&||逻辑操作符 ,用于根据前一个命令的退出状态(成功或失败)决定是否执行后续命令。这种语法称为 命令链(Command Chaining)

语法解析

bash 复制代码
[ -d student.txt ] && echo yes || echo no
  1. [ -d student.txt ]

    • 这是一个条件测试命令,用于检查 student.txt 是否是一个目录-d 参数)。
    • 如果目录存在,返回退出状态 0(成功);否则返回非 0(失败)。
  2. &&(逻辑与)

    • 仅当左侧命令成功时(退出状态为 0,才会执行右侧的命令。

    • 示例:

      bash 复制代码
      [ -d student.txt ] && echo yes

      若目录存在,则执行 echo yes;若不存在,跳过 echo yes

  3. ||(逻辑或)

    • 仅当左侧命令失败时(退出状态非 0,才会执行右侧的命令。

    • 示例:

      bash 复制代码
      [ -d student.txt ] || echo no

      若目录不存在,则执行 echo no;若存在,跳过 echo no


组合效果

  • 目录存在时
    [ -d student.txt ] 成功 → 执行 && 后的 echo yesecho yes 成功 → 跳过 || 后的 echo no

    输出:yes

  • 目录不存在时
    [ -d student.txt ] 失败 → 跳过 && 后的 echo yes → 由于左侧整体失败,执行 || 后的 echo no

    输出:no


等价于 if-else 语句

上述命令链等价于以下 if-else 结构:

bash 复制代码
if [ -d student.txt ]; then
    echo yes
else
    echo no
fi

注意事项

  1. &&|| 的优先级
    && 的优先级高于 ||,因此命令按以下分组执行:
    ( [ -d student.txt ] && echo yes ) || echo no

  2. 命令退出状态是关键

    • 每个命令的退出状态决定后续操作(0=成功,非0=失败)。
    • 例如,若 echo yes 意外失败(极罕见),也会触发 || echo no

其他常见用法

bash 复制代码
# 1. 仅当命令成功时执行操作
rm file.txt && echo "删除成功"

# 2. 仅当命令失败时执行操作
cp a.txt b.txt || echo "复制失败"

# 3. 复杂组合(注意括号分组)
make && ( echo "编译成功"; ./app ) || echo "编译失败"

通过命令链可以简洁地实现条件逻辑,但复杂的场景建议使用 if-else 增强可读性。

相关推荐
EverydayJoy^v^7 天前
Linux Shell 高级编程(3)——awk
linux·运维·shell
dingdingfish10 天前
Bash学习 - 第10章:Installing Bash
bash·make·shell·install·configure·5.3
dingdingfish11 天前
Bash学习 - 第8章:Command Line Editing,第6-8节:Programmable Completion
bash·shell·completion·complete·compgen·compopt
白云偷星子12 天前
RHCSA笔记3
shell
dingdingfish12 天前
Bash学习 - 第7章:Job Control
bash·shell·wait·job
dingdingfish12 天前
Bash学习 - 第8章:Command Line Editing,第1-2节:Intro & Readline Interaction
bash·shell·readline
only_Klein13 天前
Shell 三剑客
shell·sed·grep·awk
dingdingfish14 天前
Bash学习 - 第6章:Bash Features,第12节:Shell Compatibility Mode
bash·shell·compat·compatibility
alanesnape14 天前
一个支持在线deBug的编辑器/调试器功能详解
shell·在线编译器·在线debug
dingdingfish15 天前
Bash学习 - 第6章:Bash Features,第10节:The Restricted Shell
bash·shell·rbash·restrict