用Python编写Shell脚本

2024-10-03 19:30:02 发布

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

我是个新手。我想执行下面这样的脚本。然而,我得到的错误。请帮我修一下。你知道吗

脚本文件名:测试脚本.sh 执行:/测试脚本.sh“A”

#!/bin/bash


COStesting("Test")
{
    if [ $1 = "A" ]
    then
        Name = "Tiger"
        Gender = "Male"

    elif [ "$1" = "B" ]
     then
        Name = "Lion"
        Gender = "Male"
    fi
}
    pass=`python3 - <<END
    import subprocess
      print(Name, Gender)
    END
    ```

Tags: nametest脚本bashifbin文件名sh
2条回答
COStesting()
{
    if [ $1 == "A" ]
    then
      Name="Tiger"
    Gender="Male"

elif [ "$1" == "B" ]
 then
    Name="Lion"
    Gender="Male"
fi
}

COStesting  $1
pass=$(python3 <<END
import subprocess
print('$Name', '$Gender')
END
)

这就是你想要的,包括我和其他人在评论中提到的一些东西。你知道吗

#!/bin/bash

COStesting()
{
    local Name
    local Gender
    if [ "$1" == "A" ]
    then
        Name="Tiger"
        Gender="Male"
    elif [ "$1" == "B" ]
    then
        Name="Lion"
        Gender="Male"
    fi
    pass=$(Name="$Name" Gender="$Gender" python3 - <<-END
        from os import environ
        print(environ['Name'], environ['Gender'])
    END
    )
    echo $pass
}
  • 请确保从这里复制的缩进是用制表符而不是空格来完成的

在这里所做的:

  • 注释:Shell script with Python

    You cannot access shell variables created in a shell script inside Python as Python variables. One way is to to export shell variables into the environment, so they become environment variables, and then use the environment access mechanism in Python to retrieve the values.

    我所做的只是为python命令导出它们,而不是全局导出。

  • 注释:Shell script with Python

    COStesting("Test") isn't valid shell function syntax; you can't have anything between the () other than blanks.

  • 注释:Shell script with Python

    beware that syntax for assignment in bash is not var = val but var=val. This alone must be causing command not found for ya

  • 注释:Shell script with Python

    for indendation of here-strings you need to use <<-END and tabs not spaces

  • 您在[命令中使用了单=而不是双==作为比较运算符
  • pass是函数中的局部变量。要将其输出,您需要echo将其从函数输出到标准输出。你知道吗

要使用这个函数,您首先source <filename.sh>(除非您只是用这个函数将命令附加到文件中),然后可以像$(COStesting "$AorB")一样使用它,其中$AorB是包含'A''B'的变量。你知道吗

相关问题 更多 >