0

How do I pass random generated number in a python script eg

state = random.randint(3, 9)

os.system('bash script.sh $(state) ') #doesn't compile

to a shell script eg.

echo '{"Name": "Boom", "State": '$1'}'
istepsv
  • 21
  • 4
  • What does "doesn't compile" mean? Is there some error message? – tdelaney Oct 10 '22 at 17:03
  • 1
    sh: state: command not found {"Name": "Boom", "State": } That's the output – istepsv Oct 10 '22 at 17:05
  • 1
    `subprocess.run(['bash', 'script.sh', str(state)])` – Charles Duffy Oct 10 '22 at 17:05
  • ...but don't do that; `bash script.sh` is itself an antipattern. Scripts should choose their own interpreters by having a shebang line, and _bash_ scripts shouldn't have _sh_ extensions (bash and sh are two different interpreters); ideally they should have no extension at all. See also [Commandname extensions considered harmful](https://www.talisman.org/~erlkonig/documents/commandname-extensions-considered-harmful/). – Charles Duffy Oct 10 '22 at 17:06
  • (also, if you're going to make a shell script write JSON, use a format-aware tool like `jq` to do it; think about what happens now if someone runs `yourscript '39, "foobar": "baz"'` -- they can inject arbitrary data into your document) – Charles Duffy Oct 10 '22 at 17:09
  • Thanks! My script is an oversimplification of another script to seed database with some junk data where I couldn't pass state variable. – istepsv Oct 10 '22 at 17:18
  • `$(state)` in bash means to execute a command named _state_ and interpolate the standard output of this command. Since there is no command of this name in your PATH, you get this error message. – user1934428 Oct 11 '22 at 05:59
  • Your approach seems to be that you want to generate a complete shell command line to execute. While this is for sure possible in the simple example you posted, you are in general more flexible if you explicitly invoke the external command and pass its parameters, instead of relying on the shell command line parser. In Python, you can do this with the module called [subprocess](https://pythongeeks.org/subprocess-in-python/). – user1934428 Oct 11 '22 at 06:05

0 Answers0