当前位置: 动力学知识库 > 问答 > 编程问答 >

ssh - Bash running complex command on remote server

问题描述:


I am trying to run this command remotely with ssh:

remote_command="fname=$(echo $(basename $(ls /opt/jboss/standalone/deployments/*.ear))); mv /opt/jboss/standalone/deployments/${fname}.undeployed /opt/jboss/standalone/deployments/${fname}.dodeploy"

This command redeploys the ear file on the remote server (if the ear file with an .undeploy extension exists). There is only one ear.

The remote_command variable is passed to a function responsible to run the var remote_command:

function run_remote_command() {

local command=$1

local output=$(sshpass -pPassw ssh [email protected]_ip '$command' 2>&1)

}

The call to the function is

run_remote_command $remote_command

When I run the main script, the execution of the remote command is done:

var fname gets assigned the value of the ear filename.

But then $fname is empty when it is executed with mv.

Can someone tell me what I am missing?

Best regards,

Alain

网友答案:

Because you're not properly quoting the command, your local shell is expanding $fname

function run_remote_command() { 
  local command=$1
  # must double quote the command here
  sshpass -pPassw ssh [email protected]_ip "$command"
}

# must use single quotes here. newlines added for clarity
remote_command='
  root=/opt/jboss/standalone/deployments
  ear_files=($root/*.ear)
  if [[ "${ear_files[0]}" ]]; then 
    fname=$(basename "${ear_files[0]}") 
    mv "$root/${fname}.undeployed" "$root/${fname}.dodeploy"
  fi
'

# must double quote the command here
run_remote_command "$remote_command"

I'm assuming your shell on the remote end is bash.

分享给朋友:
您可能感兴趣的文章:
随机阅读: