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

2024-09-29 23:26:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个脚本。一个是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

Tags: echo脚本nodehomebin节点statussh
3条回答

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”等,因此需要捕获$?在要捕获execute的返回代码的命令之后直接插入另一个变量

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

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

我可以让它工作如下:

#!/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

编辑:改进的循环

相关问题 更多 >

    热门问题