How to suppress output and check whether or not a command is successful?

孤者浪人 提交于 2019-12-10 11:31:37

问题


I am trying to write a powershell script that tests if a MySQL login is successful by using $? to check if an error occurs.

I also want to suppress all output - successful or not successful - from the command.

These are the things I've tried:

mysql -u root --password=mypass -e "show databases"
If ( $? ) {
  echo "Hooray!"
} Else {
  echo "Boo!"
}

This works correctly but doesn't suppress any output.

mysql -u root --password=mypass -e "show databases" > $null

Works correctly still but does not suppress the errors if the password is wrong.

mysql -u root --password=mypass -e "show databases" 2> $null

This does not work correctly. In this example, it always prints "Boo!"

mysql -u root --password=mypass -e "show databases" > $null 2>&1

This suppresses all output correctly but only ever prints "Boo!" like before.


回答1:


Use $LASTEXITCODE -eq 0 rather than $? to reliably detect a nonzero exit code (typically signaling failure) reported by an external program.

You can then use *> $null to categorically suppress all output without having to worry about the impact of that redirection on $?:

mysql -u root --password=mypass -e "show databases" *>$null
if ($LASTEXITCODE -eq 0) {
  "Hooray!"
} else {
  "Boo!"
}

Using a redirection that involves PowerShell's error stream - either explicitly via 2> or implicitly via *> - means that if any data is received via that stream - which in the case of calling an external program means output from stderr - PowerShell sets $? to $false.

However, in the realm of external console / terminal programs, stderr isn't just used to output error information, but any information that isn't data, such as status information. Therefore, you cannot infer failure from the presence of stderr output.

External console / terminal programs communicate their success status solely via their exit code, which PowerShell reflects in the automatic $LASTEXITCODE variable.

It follows from the above that $? can be $false even if the exit code is 0, so it isn't a reliable success indicator - unlike $LASTEXTICODE.



来源:https://stackoverflow.com/questions/55622596/how-to-suppress-output-and-check-whether-or-not-a-command-is-successful

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!