繁体   English   中英

如何将以下 Python 脚本转换为 Bash 脚本?

[英]How can I convert the following Python Script to Bash Script?

我正在尝试将以下 Python 脚本转换为 Bash 脚本。 我不确定如何修复我的 bash 代码,以便它可以遵循 Python 脚本中设置的规则。 我尝试在 Bash 脚本中创建一个函数来强制执行规则,但我不断收到错误消息。

Python代码


Red     = 1
Yellow  = 2
Green   = 3

def process_light(x):
  if x == Red:
    print("red light")
    return Green

  elif x == Yellow:
    print("yellow light")
    return Red

  elif x == Green:
    print("green light")
    return Yellow

generatedLight = randrange(1, 4)
while True:
  generatedLight = process_light(generatedLight)

我的 Bash 代码

function number {
         return $[ `shuf -i 1-3 -n 1` ]
}

state=1

function colors {
         if x == 3:
         return 1
         elif x == 2:
         return 3
         elif x == 1:
         return 2
         fi
}

while [ 1 ]
do
      colors
      case $? in
      1)
              echo "The light is Green";;
      2)
              echo "The light is Yellow";;
      3)
              echo "The light is Red";;
      esac
      sleep 5
done

你非常接近......这是正确翻译的bash脚本:

#!/bin/bash

function number {
  echo $[ `shuf -i 1-3 -n 1` ]
}

state=$(number)

colors () {
  if [ $1 == 3 ]; then
    echo 1
  elif [ $1 == 2 ]; then
    echo 3
  elif [ $1 == 1 ]; then
    echo 2
  fi
}

while [ 1 ]
do
      state=$(colors $state)
      case $state in
      1)
              echo "The light is Green";;
      2)
              echo "The light is Yellow";;
      3)
              echo "The light is Red";;
      esac

      sleep 5
done

结果:

灯是黄色的

灯是红色的

灯是绿色的

灯是黄色的

...

这与原始 python 脚本的行为方式相同。 rules函数接受一个参数。 此参数是函数中的 ${1}。 我使用随机数作为参数。 祝你好运。

function number 
    {   
    echo $[ `shuf -i 1-3 -n 1` ]
    }   

function rules
    {   
    case "${1}" in
        1)  
            echo "The light is green.";;
        2)  
            echo "The light is yellow.";;
        3)  
            echo "The light is red.";;
    esac
    }   

while [ 1 ] 
do
    rules $(number)
done

暂无
暂无

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

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