首页 > 解决方案 > Bash script variable not being passed via ssh

问题描述

I have a bash script which ssh's to a server, and depending on the status of a variable performs a task:

#!/bin/bash

foo=$1
ssh user@host.com '
echo In host
if [ "$foo" == "yes" ]; then
   echo "Foo!"
fi
'

When I run sh script.sh yes, although the ssh command works, the conditional evaluates to false. I can see this if I echo $foo - it prints an empty line. How can I access the value of foo within the ssh command?

标签: bash

解决方案


变量不会传输到远程机器。您可以在通过 ssh 发送的代码中扩展该变量,但您必须非常小心,因为它为不受控制的代码执行打开了大门:

#!/bin/bash

foo=$1
ssh user@host.com '
echo In host
if [ "'"$foo"'" == "yes" ]; then
   echo "Foo!"
fi
'

现在想象一下(不要尝试)如果foo='$(rm -rf /)'.


推荐阅读