简体   繁体   English

如何在shell sh脚本中匆忙获取错误及其代码?

[英]How to get error and their codes in drush in a shell sh script?

I'm launching some drush commands inside a shell script sh. 我正在shell脚本sh中启动一些drush命令。 How can i get if the command has terminated with no error? 如果命令已正确终止,我如何获得? And, in case of error, how can i get the error and present it to the user executing the script? 而且,如果出现错误,我该如何获取错误并将其呈现给执行脚本的用户?

As I said in my first comment if you put together a shell script with drush commands the user executing the script will see all the messages drush writes to the console. 正如我在第一条评论中所说,如果将shell脚本与drush命令放在一起,执行该脚本的用户将看到drush写入控制台的所有消息。 But if you want to write a more complex script, ie with checks for errors etc. then here is a short example that should get you started: 但是,如果您想编写一个更复杂的脚本,即检查错误等,那么这是一个简短的示例,可以帮助您入门:

msg=$(drush blah 2>&1)
if [[ "$msg" =~ error* ]]
then
  echo "we had an error!"
else
  echo "success"
fi
msg=$(drush cc all 2>&1)
echo $msg

NOTE: this script assumes that you have a bash shell. 注意:此脚本假定您具有bash shell。

The construct $(command) is used to pipe stdout to a variable. 构造$(command)用于将stdout传递给变量。 Since drush pipes error messages to stderr we also need suffix the drush command with 2>&1 which is a command to redirect stderr to stdout. 由于drush将错误消息通过管道传递到stderr,因此我们还需要在drush命令后缀2>&1 ,该命令是将stderr重定向到stdout的命令。 The if check is then basically a substring check for "error" in the $msg variable. 然后, if检查基本上是$ msg变量中“错误”的子字符串检查。

Here is a good resource for Bash programming: 这是Bash编程的好资源:

http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO.html http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO.html

Hope this helps. 希望这可以帮助。

=========== EDIT ============= ===========编辑=============

if you are in a Bourne shell you would use the following to redirect output to a variable: 如果您在Bourne Shell中,则可以使用以下命令将输出重定向到变量:

msg=`drush cc all 2>&1`

You should be able to see which shell you are using by executing echo $SHELL 您应该能够通过执行echo $SHELL来查看正在使用的shell。

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

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