简体   繁体   中英

Variables in remote SSH session

I have some inconsistent behavior in my bash script. There are variables, and all of them have values assigned to them, I confirm them by echoing the values at the beginning of the script.

However, when passing them to a remote SSH session, one variable has value, whereas the other one appear to be blank. I am pretty sure I am not overwriting the variable's value.

# Script input arguments
USER=$1
SERVER=$2
# Other vars
PFX=$8
#
ADDRESS=$USER@$SERVER

function run {
    ssh $ADDRESS /bin/bash $@
}

# Script body, some stuff happens here
run << "SSHCONNECTION2"
    sudo mv "/home/$USER/$PFX" "/home/$USER/certs/"
SSHCONNECTION2

So, the output of mv is

error 03-Jan-2017 17:20:39 mv: cannot move '/home/admin/' to a subdirectory of itself, '/home/admin/certs/admin'

Can somebody give me a hint what am I doing wrong? Thank you.

USER had a remote value because USER always has a value: By default, it's the current user account on all POSIX systems . To avoid conflicting with system-defined variable names, you should use lower-case names for your own shell and environment variables (the former because setting a shell variable with a name that overlaps an environment variable will implicitly overwrite the latter).

#!/bin/bash
#      ^^^^ - not /bin/sh; printf %q (thus, eval-safe quoting) is a bash extension

user=$1
pfx=$8

# Tell the shell to quote your variables to be eval-safe!
printf -v user_q '%q' "$user"
printf -v pfx_q '%q' "$pfx"

# ...then you can use those eval-safe version in your heredoc
run << SSHCONNECTION2
    # because the values are self-quoted, don't put their expansions inside quotes
    sudo mv /home/$user_q/$pfx_q /home/$user_q/certs/
SSHCONNECTION2

Notes:

  • The sigil ( SSHCONNECTION2 ) is intentionally unquoted to allow expansions to occur.
  • Using lower-case variable names avoids inadvertently conflicting with names meaningful to the shell or system.

The above is a bit unfortunate, because the literal contents of the SSHCONNECTION2 heredoc isn't code that could safely be run directly in a shell. Consider this answer instead .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM