5

I'm attempting to use python to dynamically create bash aliases (like, for example, aliases to log in to a set of servers). I'd love to be able to do something like this:

from subprocess import call
SERVERS = [
    ("example", "[email protected]"),
    #more servers in list
]    

for server in SERVERS:
    call('alias %s="ssh %s"' % (server[0], server[1]), shell=True)

The problem is that subprocess launches the jobs in a separate shell session, so the program runs fine, but does nothing to the shell session I run it from.

The same problem occurs with python's os.system or attempting to print the commands and pipe them to bash (all of these create the aliases, but in a new shell that is promptly destroyed after the program finishes).

Ultimately, the goal of this is to run this script from .bashrc

How does one do this?

3
  • 1
    This seems far more complicated than just defining the aliases in bash without involving Python. Commented Feb 11, 2014 at 12:45
  • 1
    @chepner Obviously if this were the end-all-be-all, Python would be inappropriate. The point of doing this is not just to generate this particular set of aliases dynamically, but also to be able to generate other aliases (such as uploading files to servers) dynamically as well. Commented Feb 11, 2014 at 23:09
  • stackoverflow.com/staging-ground/79161754 it would be nice if mergeable somehow. Externally, meaning not logged in, this link is with status 404. Commented Nov 6, 2024 at 12:43

1 Answer 1

7

You should write the alias commands to stdout. (eg. just use print).
Then the shell that is calling the Python script can run the alias commands itself.

As commented by @thatotherguy

eval "$(python yourscript.py)"

in your .bashrc should do it

Sign up to request clarification or add additional context in comments.

3 Comments

I'd like for the aliases to be created automatically. Ideally, I'm calling this script from bashrc
@Zags Use gnibbler's suggestion and invoke it as eval "$(python yourscript.py)" in your .bashrc.
@thatotherguy post it as an answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.