1

Modify .bash_aliases with Python

So I've been trying to modify .bash_aliases programatically for a while now, and I've been running into issues with every method I've tried.

  • Running my script using sudo python3 myscript.py causes the script to modify the .bash_aliases file of the root user. I can't find a way to determine what user ran the script to modify their file.
  • Trying to use a shell command such as sudo echo "my string" >> ~/.bash_aliases gets an error: sh: 1: cannot create /home/migue/.bash_aliases: Permission denied, presumably because sudo can't display its password prompt when I call it programatically.
  • I can't find a way to temporarily get root permissions after determining the full path (ie expanding ~) of the file.

Basically, I'd love to know any reasonable method to modify and append to .bash_aliases through a Python script. I haven't found any questions on this where the solutions worked for me.

I'd prefer for this method to not require any non-standard modules, as installing them will just make the process less seamless for people who use the script.

Submitted July 24th 2021 by Admin

Answers
0

I can't find a way to determine what user ran the script to modify their file.

You can reference the file ~/.bash_aliases in your script and run it without sudo, unless your current user is root.

EDIT: You simply need to add write privileges to .bash_aliases for every user it belongs to.

Admin | 1 month ago



Relevant Questions