This does what you want; incorporating some stuff that i and others mentioned in comments.
#!/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
}
- Please ensure that in what you copy from here the indentation is done with tab characters and not with spaces
What was done here:
comment: 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.
What i did was exporting them for just the python
command, instead of globally.
- comment: Shell script with Python
COStesting("Test")
isn't valid shell function syntax; you can't have anything between the (
)
other than blanks.
- comment: 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
- comment: Shell script with Python
for indendation of here-strings you need to use <<-END
and tabs not spaces
- you used single
=
instead of double ==
for comparison operator in the [
command
pass
was a local variable in function. to have it out, you need to echo
it from the function onto standard output.
to use this function, you first source <filename.sh>
(unless you just append commands to the file with this function) and then you can use it like $(COStesting "$AorB")
where $AorB
is some variable containing either 'A'
or 'B'
.