简体   繁体   English

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

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

I am trying to convert the following Python Script into a Bash Script.我正在尝试将以下 Python 脚本转换为 Bash 脚本。 I am not sure how to fix my bash code so it can follow the rules set in the Python Script.我不确定如何修复我的 bash 代码,以便它可以遵循 Python 脚本中设置的规则。 I tried creating a function in the Bash Script to enforce the rules, but I keep recieving errors.我尝试在 Bash 脚本中创建一个函数来强制执行规则,但我不断收到错误消息。

Python Code 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)

My Bash Code我的 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

You were very close... here is the correctly translated bash script:你非常接近......这是正确翻译的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

Result:结果:

The light is Yellow灯是黄色的

The light is Red灯是红色的

The light is Green灯是绿色的

The light is Yellow灯是黄色的

... ...

This behaves the same way as your original python script.这与原始 python 脚本的行为方式相同。 The rules function takes an argument. rules函数接受一个参数。 This argument is the ${1} in the function.此参数是函数中的 ${1}。 I use the random number as the argument.我使用随机数作为参数。 Best of luck.祝你好运。

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