0

I'm trying to run a non-interactive command within a login shell (using su - or sudo -i) but couldn't make it work so far.

Within ~/.bashrc I have sourced a script which sets all variables my application needs. When I do an interactive login su - username I can see all my variables there and if I run my application it works fine. However, when I try to execute my application by using su - username -c 'command' the necessary variables are not being set. In other words, it seems su - is incompatible with -c option. The same happens with sudo -i -u user command.

I have searched tons of questions but couldn't find an answer to this specific behavior.

According to bash man pages:

When bash is invoked as an interactive login shell, or as a non-interactive
shell with the `--login` option, it first reads and executes commands from the
file `/etc/profile`, if that file exists. After reading that file, it looks for
`~/.bash_profile`, `~/.bash_login`, and `~/.profile`, in that order, and reads and
executes commands from the first one that exists and is readable. The
`--noprofile` option may be used when the shell is started to inhibit this
behavior.

The above behavior is not working as ~/.profile executes ~/.bashrc and it in turn sources the script which sets all variables.

How can I execute a non-interactive login shell?

Thank you

Félicien
  • 1,203
felima
  • 1
  • 1
  • 2

1 Answers1

0

You can source the variable file in your script. In your script, include the following line before referencing any of the variables:

source full_path_to_variable_file

This will read your variables into the script's session. You must use the full literal path (no aliases), starting with the root directory'/', so for example if your home directory's .bash_aliases defines your variables:

source /home/felima/.bash_aliases

On the command line '.' has the same effect

. ~/.bash_aliases

But in scripts using 'source' is more clear.