How to modify environment variables before executing a command

Malte Forkel malte.forkel at berlin.de
Thu Dec 3 05:25:09 EST 2009


>> I'd like to access and modify shell environment variables before
>> executing a command on a remote host via ssh. Unfortenatly, I can't
>> figure out the proper way to do this...

Thanks for the suggestions I received!

Karlan T. Mitchell schrieb:
> ~/.bashrc I believe.  Profile is for local terminals.....pretty sure at
> least. Hope this helps

Jim Rees schrieb:
> The bash man page suggests you should be able to do this:
> ~/.ssh/environment
> BASH_ENV=.bash_profile

I extended my test scenario to four configuration files on the server:
    # .ssh/environment
    VAR1=$(date)
    BASH_ENV=~/.ssh/ssh_profile

    # .ssh/rc
    echo ".ssh/rc"
    VAR2=$(date)
    export VAR2

    # .bashrc
    echo ".bashrc"
    VAR3=$(date)
    export VAR3

    # ~/.ssh/ssh_profile
    echo ".ssh/ssh_profile"
    VAR4=$(date)
    export VAR4

Now, when I execute
    $ ssh server env | grep -E -e '^\.' -e VAR
I get
    .ssh/ssh_profile
    .ssh/rc
    .bashrc
    VAR1=$(date)
    VAR3=Mi 2. Dez 18:16:33 CET 2009
So all four files are read or sourced, respectively.

I hadn't noticed that ~/.bashrc is sourced because it starts with
    # If not running interactively, don't do anything
    [ -z "$PS1" ] && return
which terminates it in the ssh context. But above that test I could
insert a test for some flag set in .ssh/environment and setup the shell
variables I need for ssh. Still, that seems a little awkward as .bashrc
is sourced every time any shell is created with the default
configuration files.

I'm still looking for a more ssh-specific solution. Unfortenately, the
variables exported from the two ssh-specific files .ssh/rc and
.ssh/ssh_profile don't make it into the environment. Why is that?

A secondary problem with using BASH_ENV could be that its value is
evaluated by every non-interactive shell. So, if I use ssh to login to
the server and then run a script with bash, the file specified by
BASH_ENV is sourced. For example, with the above setup:
    $ echo "echo foo" > say_foo.sh
    $ bash say_foo.sh
    .ssh/ssh_profile
    foo

Any more suggestions on how to modify environment variables before
executing a command via ssh?

Thanks, Malte






More information about the openssh-unix-dev mailing list