简体   繁体   English

测试命令和重定向bas​​h

[英]Test command and redirection bash

Why does test > file exit with 1 while test arg1 > arg2 exit with 0 ? 为什么test > file以1退出而test arg1 > arg2以0退出?

I thought that in test arg1 > arg2 , test arg1 is applied first then the output(it has none) written to file arg2 and since the last command(redirection) was successful the exit is 0. But so should the first case. 我以为在test arg1 > arg2 ,首先应用了test arg1然后将输出(没有输出)写入文件arg2并且由于最后一个命令(重定向)成功,所以退出为0。但是第一种情况也应该如此。 I am a bit confused. 我有点困惑。

Redirection is not a command. 重定向不是命令。

| creates a new command, because not only the is output of the previous command "piped" somewhere else, but also another command is executed on that output. 之所以创建新命令,是因为不仅先前命令“ piped”的输出是在其他位置,而且在该输出上还会执行另一个命令。 For example, 例如,

ls | grep 'abc' ls | grep 'abc' will exit 1 if nothing matches that pattern, regardless of whether ls completed successfully or not). 如果没有任何匹配的模式,则ls | grep 'abc'将退出1,无论ls是否成功完成。 The exit status you see with $? 您看到的带有$?的退出状态$? is the status of the last pipe. 是最后一个管道的状态。

Redirection is not the same, because it doesn't give the output to the next command in line, just to a file. 重定向是不一样的,因为它不会将输出仅提供给文件中的下一个命令。 Note that redirection can make you return 1 when your command would otherwise have worked because you don't have permissions to write to the file. 请注意,重定向可以使你返回1,当你命令,否则工作过,因为你没有权限写入文件。 In that case, your command won't be executed. 在这种情况下,您的命令将不会执行。

TL;DR: A command requires a valid redirection to run. TL; DR:命令需要有效的重定向才能运行。 If it can run, the exit status will be the exit status of the command. 如果可以运行,则退出状态将是命令的退出状态。 Exit status of redirection is the OR of the command and the redirection (0 OR 1, 1 OR 1, 1 OR 0 will all return 1; only a successful redirection and successful command returns 0) 重定向的退出状态是命令的OR,并且重定向(0 OR 1、1 OR 1、1 OR 0都将返回1;只有成功的重定向和成功的命令才返回0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM