0

I have a simple shell script script.sh:

echo "ubuntu:$1" | sudo chpasswd

I need to open the script, read it, insert the argument, and save it as a string like so: 'echo "ubuntu:arg_passed_when_opening" | sudo chpasswd' using Python.

All the options suggested here actually execute the script, which is not what I want.

Any suggestions?

ilmoi
  • 1,994
  • 2
  • 21
  • 45
  • Sounds like a job for regex. Open the file, do `re.sub("$1", arg, file_contents)`, and you're done. – ThisIsAQuestion Dec 04 '20 at 19:19
  • 1
    Why a regex? It's a simple string replace. – fuenfundachtzig Dec 04 '20 at 19:20
  • Yeah, that'd work too – ThisIsAQuestion Dec 04 '20 at 19:20
  • 1
    The shell script is a file, and you can open it as a file and read/write whatever you want. (PS: It really sounds like you've misunderstood the task here) – that other guy Dec 04 '20 at 19:20
  • Why are you opening and modifying a shell script, versus calling it with an argument? This is an unusual and error prone request. Could it be an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)? Perhaps you could tell us why you're doing it and what the underlying problem you're trying to solve is. – John Kugelman Dec 04 '20 at 19:45

1 Answers1

2

You would do this the same way that you read any text file, and we can use sys.argv to get the argument passed when running the python script.

Ex:

import sys

with open('script.sh', 'r') as sfile:
    modified_file_contents = sfile.read().replace('$1', sys.argv[1])

With this method, modified_file_contents is a string containing the text of the file, but with the specified variable replaced with the argument passed to the python script when it was run.

John Paul R
  • 649
  • 5
  • 10