gpt4 book ai didi

linux - Unix 测试是否存在或文件

转载 作者:太空狗 更新时间:2023-10-29 11:38:38 24 4
gpt4 key购买 nike

[ -f /tmp/myfile.txt ] && echo "File exists" || echo "No such file"

这是如何运作的?特别是 &&|| 的评估。

最佳答案

&&|| 是控制运算符,它们根据先前命令的退出状态确定是否应执行以下命令。来自 man (1) bash:

The control operators && and || denote AND lists and OR lists, respectively. An AND list has the form

  command1 && command2

command2 is executed if, and only if, command1 returns an exit status of zero.

An OR list has the form

  command1 || command2

command2 is executed if and only if command1 returns a non-zero exit status. The return status of AND and OR lists is the exit status of the last command executed in the list.

[test,如果命令通过测试,则返回 退出状态。来自帮助测试:

test: test [expr] Exits with a status of 0 (true) or 1 (false) depending on the evaluation of EXPR.

所以当你这样做的时候

[ -f /tmp/myfile.txt ] && echo foo || echo bar

你真正想说的是(请仔细阅读)如果文件存在,回显 foo。如果文件不存在echo foo命令失败,回显栏。

这是这些控制运算符与 if...then 命令之间的细微但关键的区别。

关于linux - Unix 测试是否存在或文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14484017/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com