MacOSX how to autorun a script after su - root?

2019-09-13 03:22发布

Lets assume i am normal user, the i will switch to root:

user ~ $ su - root
Password: 
root ~ #

So once i logged in as root, i want to run following command automatically:

source .bash_profile

How can i have that above command run automatically please?

2条回答
2楼-- · 2019-09-13 03:34

First of all, when you switch to root user, you will be still your regular user's home directory. Which .bash_profile you want to execute? /Users/myuser/.bash_profile or root's /var/root/.bash_profile?

Regardless of what you would like to execute, you can edit /var/root/.bashrc (if you don't have it, create one) and add your command there.

查看更多
Animai°情兽
3楼-- · 2019-09-13 03:54

According to the bash man page, .bash_profile is executed for login shells, while .bashrc is executed for interactive non-login shells.

In your case, you don't need to source .bash_profile like this.

You just need to put source .bash_profile in your root's .bashrc file

if [ -f ~/.bash_profile ]; then
   source ~/.bash_profile
fi

Read me for better understanding of .bash_profile and .bashrc

Update

Example:

[root@sgeorge-ld ~]# cat .bashrc | tail -1
echo "Testing .bashrc for a stack query"
[root@sgeorge-ld ~]# exit
logout
[sgeorge@sgeorge-ld ~]$ su - root
Password: 
Testing .bashrc for a stack query
[root@sgeorge-ld ~]# 
查看更多
登录 后发表回答