我需要使用 运行我的脚本sudo
,因为它包含使用 apt 安装程序的命令。所以我这样做:
sudo ./myscript.sh
内容:
#!/bin/bash
# add alias .bashrc (work)
echo "alias myupgrade='sudo aptitude -y safe-upgrade && sudo updatedb'" | sudo tee -a /home/my_user/.bashrc > /dev/null
# or
# sudo -u my_user bash -c "echo alias myupgrade=\"'sudo aptitude -y safe-upgrade && sudo updatedb'\"" >> ~/.bashrc
# load changes (doesn't work)
sudo -u my_user bash -c "source /home/my_user/.bashrc"
# rest of script (not relevant for the question). e.g:
apt -y install foo bar etc
我的脚本将别名添加到 bashrc 很好,但其余的不起作用。我在脚本中尝试了这些命令,但没有成功:
# doesn't work
sudo su - my_user -c "source /home/my_user/.bashrc"
source /home/my_user/.bashrc
source ~/.bashrc
sudo bash --rcfile /home/my_user/.bashrc
有帮助吗(ubuntu 22.04)?提前致谢
更新(解决方法):
这里发布了一个解决方法,打开终端并运行临时别名:
# create temporary aliases
alias myupgrade='apt-get update && apt-get dist-upgrade && aptitude -y safe-upgrade && updatedb'
# creating temporary sudo aliases
alias sudo='sudo '
# run temporary aliases (doesn't work inside bash script)
sudo myupgrade
但它在 bash 脚本中不起作用