简体   繁体   English

如何根据第一个脚本的结果从另一个shell脚本调用shell脚本?

[英]How to call a shell script from another shell script based on the first script's result?

Shell script 1.sh is like Shell脚本1.sh就像

#/bin/bash

if some java command;
then 
exit 1;
else    
exit 0;
fi

Shell script 2.sh will determine its execution based on the result (1 or 0) from 1.sh Shell脚本2.sh将根据1.sh的结果(1或0)确定其执行

#/bin/bash
readyToDoSomethingIfOne=$(1.sh)

if($readyToDoSomethingIfOne=="1");
then
echo "ready to go";
else    
echo "Not ready yet" ;
fi

It looks like exit command from 1.sh does not pass the value to 2.sh. 看起来像1.sh的exit命令没有将值传递给2.sh. Is there any good way to do so? 有没有好办法呢?

By the way, 1.sh and 2.sh have to be separated for business reasons. 顺便说一下,出于商业原因,必须将1.sh和2.sh分开。

Thanks 谢谢

#/bin/bash

if 1.sh; then
  echo "ready to go";
else    
  echo "Not ready yet" ;
fi
#/bin/bash
if readyToDoSomethingIfOne=$(1.sh); then # Just use the exit status of the initial script directly.
    …
else
    echo 'nope!'
fi

If you don't actually need the variable at all, just run the script like this: 如果您根本不需要变量,只需运行如下脚本:

if ./1.sh; then
  echo "Not ready yet"
  return / exit / continue # Not enough context to know which exit approach is best.
fi

The construct 构造

VAR=$(COMMAND)

assigns the output of COMMAND to the variable VAR. 将COMMAND的输出分配给变量VAR。 You can get the exit status of the last command from the automatic variable $? 您可以从自动变量$?获取最后一个命令的退出状态 $? . That is 那是

COMMAND
case $? in
  0)
      # do this
      ;;
  1)
      # do that
      ;;
  *)
      # do something else
      ;;
esac

If you only want to distinguish between success ( $? == 0 ) and failure ( $? != 0 ) then you can use the simpler if construct as in your script1.sh . 如果您只想区分成功( $? == 0 )和失败( $? != 0 ),那么您可以在script1.sh使用更简单的if构造。

If using $? 如果使用$? , watch out that it changes after every command, so if you need the value for later use, save it in a variable. ,注意它在每个命令后都会发生变化,因此如果您需要该值供以后使用,请将其保存在变量中。

COMMAND
status=$?
# now use $status

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

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