I am trying to write a script which runs a command as a different user, but under the environment set-up by my own .bashrc. I would like the script to work for our entire team.

Here is my attempt to source my .bashrc file from sudo:

homedir=$(echo ~)
cmd="source $homedir/.bashrc; <SOME COMMAND>"
sudo -u <other_user> bash -c $cmd

I am getting an error:

<my_home_dir>/.bashrc: line 0: source: filename argument required
source: usage: source filename [arguments]

However, when I specify the soruce command directly, instead of keeping it in the $cmd variable, I am not getting the error. Namely, the following snippet works flawlessly:

sudo -u <other_user> bash -c 'source <my_home_dir>/.bashrc; <SOME COMMAND>'

What would be the source of the problem? How can I make the script generic, without making every team member specify their own home directory?

(the user names and home directories are obfuscated on purpose)

  • Sole ~ is replaced by the value of the variable HOME. Assigning to another variable in a relatively complex way (homedir=$(echo ~)) is completely unnecessary. Simply use $HOME instead of $homedir in the next line. Feb 12, 2020 at 10:12

1 Answer 1


Proper use of variables suggests to use "${cmd}" instead of $cmd. The "" is just what you are missing. Your whole endeavour could probably be tackled slightly more elegantly b use of the --rcfile parameter of bash itself.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .