Passing variables in remote ssh command

前端 未结 7 1710
余生分开走
余生分开走 2020-12-04 11:59

I want to be able to run a command from my machine using ssh and pass through the environment variable $BUILD_NUMBER

Here\'s what I\'m trying:



        
7条回答
  •  孤街浪徒
    2020-12-04 12:11

    (This answer might seem needlessly complicated, but it’s easily extensible and robust regarding whitespace and special characters, as far as I know.)

    You can feed data right through the standard input of the ssh command and read that from the remote location.

    In the following example,

    1. an indexed array is filled (for convenience) with the names of the variables whose values you want to retrieve on the remote side.
    2. For each of those variables, we give to ssh a null-terminated line giving the name and value of the variable.
    3. In the shh command itself, we loop through these lines to initialise the required variables.
    # Initialize examples of variables.
    # The first one even contains whitespace and a newline.
    readonly FOO=$'apjlljs ailsi \n ajlls\t éjij'
    readonly BAR=ygnàgyààynygbjrbjrb
    
    # Make a list of what you want to pass through SSH.
    # (The “unset” is just in case someone exported
    # an associative array with this name.)
    unset -v VAR_NAMES
    readonly VAR_NAMES=(
        FOO
        BAR
    )
    
    for name in "${VAR_NAMES[@]}"
    do
        printf '%s %s\0' "$name" "${!name}"
    done | ssh user@somehost.com '
        while read -rd '"''"' name value
        do
            export "$name"="$value"
        done
    
        # Check
        printf "FOO = [%q]; BAR = [%q]\n" "$FOO" "$BAR"
    '
    

    Output:

    FOO = [$'apjlljs ailsi \n ajlls\t éjij']; BAR = [ygnàgyààynygbjrbjrb]
    

    If you don’t need to export those, you should be able to use declare instead of export.

    A really simplified version (if you don’t need the extensibility, have a single variable to process, etc.) would look like:

    $ ssh user@somehost.com 'read foo' <<< "$foo"
    

提交回复
热议问题