如何 运行 一个命令基于 shell 脚本中另一个命令的输出?

How to run a command based on output of another command in shell script?

我有两个脚本。一个是 Python 脚本,如果一切都成功,那么它会打印 status=done 然后还有另一个名为 "node-red".

的服务

现在,如果它读取 status=done,那么它 运行 就是节点红色。如果没有 status-done 则它会再次尝试 运行 Python 脚本,直到收到 status=done.

我该怎么做?

#!/bin/sh
python3 /home/pi/cryptoauthtools/python/examples/mikro_file.py
pid=$!
echo "Waiting for python script to execute"
if [ "${pid}" = "status=done" ]; then
   echo Job 1 exited with status $?
   node-red
fi

https://www.mylinuxplace.com/bash-special-variables/

$! Process number of last background command.

您需要捕获命令的输出,而不是最后一个后台任务的 PID。

#!/bin/sh
echo "Waiting for python script to execute"
output=$(python3 /home/pi/cryptoauthtools/python/examples/mikro_file.py)
exit_code=$?

if [ "$output" = "status=done" ]; then
   echo "Job 1 exited with status $exit_code"
   node-red

另外 $?是最后一个命令的退出代码,包括任何 "echos" 等。所以你需要捕获 $?在要捕获执行 return 代码的命令之后直接进入另一个变量

此外,python 脚本会在 运行 之后执行回显行,因此最好在执行脚本之前通知用户该命令。

我可以让它像下面这样工作:

#!/bin/sh 
test="$(python3 test.py)"
echo "Waiting for python script to execute"
if [ "${test}" = "status=done" ]; then
    echo Job 1 exited with status $?
    echo "node-red"
else
  test="$(python3 test.py)"
  while [ "$test" != "status=done" ]
  do
    test="$(python3 test.py)"
  done
    echo "Waiting for python script to execute"
    if [ "${test}" = "status=done" ]; then
      echo Job 1 exited with status $? 
      echo "node-red"
    fi
fi

为了模拟不同的输出,我的 python 文件是这样的:

import random 

status = ['done', 'wip', 'clarify']

print(f'status={random.choice(status)}')

这是我得到的输出:

/tmp$ ./script.sh
Waiting for python script to execute
Job 1 exited with status 0
node-red

/tmp$ ./script.sh
Waiting for python script to execute
Job 1 exited with status 0
node-red

/tmp$ ./script.sh  
Waiting for python script to execute 
Waiting for python script to execute 
Waiting for python script to execute 
Job 1 exited with status 0
node-red

/tmp$ ./script.sh  
Waiting for python script to execute 
Job 1 exited with status 0
node-red

编辑:改进循环

If there is no "status-done" then it try to run the python script again until it receives the "status=done"

echo "Waiting for python script to success!"
while
      output=$(python3 /home/pi/cryptoauthtools/python/examples/mikro_file.py)
      [ "$output" != 'status=done' ]
do
      echo "The python script did not output 'status=done', repeating..."
      sleep 1
done
echo "Yay! python succeeded. Let's run node-red"
node-red

虽然 python 脚本的输出不是 status=done,但请重复。然后 运行 node-red.