希望可以注意到这一点,现在我已经遇到了:
我已经知道可以使用test
( [
) 命令测试文件是否存在:
$ touch exists.file
$ if [ -f exists.file ] ; then echo "yes" ; else echo "no" ; fi
yes
$ if [ -f noexists.file ] ; then echo "yes" ; else echo "no" ; fi
no
Run Code Online (Sandbox Code Playgroud)
...但这有点打字:)
所以,如果有一个“默认”单个命令,我会徘徊,它将文件存在结果返回到stdout
?
我也可以使用test
退出状态$?
:
$ test -f exists.file ; echo $?
0
$ test -f noexists.file ; echo $?
1
Run Code Online (Sandbox Code Playgroud)
...但这仍然是两个命令 - 并且逻辑也是“反向”(成功为 0,失败为非零)。
我问的原因是我需要测试 中的文件是否存在gnuplot
,其 "system("command")
将来自 stdout 的结果字符流作为字符串返回。 "; 在gnuplot
我可以直接做:
gnuplot> if (0) { print "yes" } else { print "no" }
no
gnuplot> if (1) { print "yes" } else { print "no" }
yes
Run Code Online (Sandbox Code Playgroud)
所以我基本上希望能够写出这样的东西(伪):
gnuplot> file_exists = system("check_file --stdout exists.file")
gnuplot> if (file_exists) { print "yes" } else { print "no" }
yes
Run Code Online (Sandbox Code Playgroud)
...不幸的是,我不能直接通过test
and使用它$?
:
gnuplot> file_exists = system("test -f exists.file; echo $?")
gnuplot> if (file_exists) { print "yes" } else { print "no" }
no
Run Code Online (Sandbox Code Playgroud)
...我不得不颠倒逻辑。
所以,我基本上必须想出一种自定义脚本解决方案(或将脚本内联编写为单行)......我想,如果已经有一个可以打印 0 或 1(或自定义消息)到标准输出文件存在,然后我不必这样做 :)
(请注意,这ls
可能是一个候选,但它的 stdout 输出过于冗长;如果我想避免这种情况,我将不得不抑制所有输出并再次返回存在状态,如
$ ls exists.file 1>/dev/null 2>/dev/null ; echo $?
0
$ ls noexists.file 1>/dev/null 2>/dev/null ; echo $?
2
Run Code Online (Sandbox Code Playgroud)
......但这又是两个命令(和更多的打字)和“反转”逻辑......)
那么,是否有一个默认命令可以在 Linux 中执行此操作?
Sté*_*las 10
听起来你需要反转退出状态,所以你可以这样做:
system("[ ! -e file ]; echo $?")
Run Code Online (Sandbox Code Playgroud)
或者:
system("[ -e file ]; echo $((!$?))")
Run Code Online (Sandbox Code Playgroud)
(请注意,这-f
是针对文件是否存在并且是常规文件)。
小智 9
使用这个单一的 bash 命令:
[ -f /home/user/file_name ]
Run Code Online (Sandbox Code Playgroud)
在[]
成功进行测试并返回0
归档时间: |
|
查看次数: |
122501 次 |
最近记录: |