单个命令检查文件是否存在,并将消息(自定义)打印到stdout?


18

希望能注意到这一点,因为我已经遇到了它:

我已经知道可以使用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

...但是在那儿输入了一些内容:)所以,我在徘徊如果有一个“默认”的单个命令,它将把文件的存在结果返回给stdout

我也可以使用test退出状态$?

$ test -f exists.file ; echo $?
0
$ test -f noexists.file ; echo $?
1

...但这仍然是两个命令-逻辑也是“反”(0表示成功,非零表示失败)。

我要问的原因是我需要测试中的文件是否存在gnuplot,该文件的“ system("command")将来自stdout的结果字符流作为字符串返回 ”。在gnuplot我可以直接做:

gnuplot> if (0) { print "yes" } else { print "no" }
no
gnuplot> if (1) { print "yes" } else { print "no" }
yes

所以我基本上希望能够写这样的东西(伪):

gnuplot> file_exists = system("check_file --stdout exists.file")
gnuplot> if (file_exists)  { print "yes" } else { print "no" }
yes

...不幸的是,我不能通过test和直接使用它$?

gnuplot> file_exists = system("test -f exists.file; echo $?")
gnuplot> if (file_exists)  { print "yes" } else { print "no" }
no

...我必须颠倒逻辑。

因此,我基本上必须提出一种自定义脚本解决方案(或以单线形式内联编写脚本)...并且我认为,如果已经有了可以打印0或1(或一条自定义消息)到stdout以确保文件存在,那么我不必这样做 :)

(请注意,这ls可能是一个候选者,但是它的stdout输出过于冗长;如果要避免这种情况,我必须抑制所有输出并再次返回存在状态,如

$ ls exists.file 1>/dev/null 2>/dev/null ; echo $? 
0
$ ls noexists.file 1>/dev/null 2>/dev/null ; echo $? 
2

...但这又是两个命令(以及更多的键入内容)和“反转”逻辑...)

那么,在Linux中有没有一个可以执行此操作的默认命令?


2
怎么样( [ -f py_concur.py ] && echo "file exists" ) || echo "file does not exist"
iruvar

Answers:


9

听起来您需要将退出状态反转,因此可以执行以下操作:

system("[ ! -e file ]; echo $?")

要么:

system("[ -e file ]; echo $((!$?))")

(注意-f如果文件存在且是一个普通文件)。


5

使用以下单个bash命令:

 [ -f /home/user/file_name ]

[]成功进行测试并返回0


3
如果出现任何一种情况,都不会返回任何内容
-CentOS

1
在macOS上运行良好。
Joshua Pinter

1
您可以使用它来通过&&and ||运算符有条件地运行命令:[ -f /home/user/file_name ] || echo "File not present"以及[ -f /home/user/file_name ] && echo "File is present"
charlesreid1

1
@ charlesreid1的工作可以了,谢谢!
Marta Karas

1

怎样通过以下方式“反转逻辑”:

file_exists = 1-system("test -f exists.file; echo $?")

-1

这有效:

pwsh -c Test-Path /etc/passwd

...如果您已安装PowerShell。如果路径存在,则返回字符串“ True”,否则返回“ False”。(对于这个答案,我是否获得“讽刺地无助”的分数?)

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.