简体   繁体   中英

what's wrong with my bash script?

ssh -f $user@$machine_name "cd $path; shard_path=`find . -name \"shard0\"`; cd $shard_path; mkdir temp"

The directory structure is $path/node0/shard0

In this script, the var shard_path is null, why? And the directory temp is constructed in the ~/ but not in the shard0 .

Because you're using double quotes around the command to send to the server, that is being expanded locally. It's trying to substitute $path and $shard_path based on their local values, and since $shard_path isn't defined locally, it expands to nothing.

You can avoid a lot of these quoting issues by using single quotes for the command to be executed on the server. The exact quoting that you need depends on exactly where these variables are defined. But from your comments, it sounds like this is the command that you need:

ssh -f $user@$machine_name "cd $path;"'shard_path=$(find . -name "shard0"); cd $shard_path; mkdir temp'

From your discussion with Brian Campbell, I assume that the $path variable is on the local client and $shard_path is on the remote location.

Then try the following:

ssh -f xce@ns20.xce.n.xiaonei.com "echo $path; cd $path; shard_path=\$(find . -name \"shard0\"); echo \$shard_path;"

Note: If there is a possibility that there are multiple files called 'shard0', find will output many paths, so you might want to use
shard_path_array=( \\$(find . -name \\"shard0\\") );
This puts find's output into an array, and you can then switch to one path using for example
cd \\${shard_path_array[0]} (on the remote machine)

$path is being expanded locally before the command is sent to the destination machine via ssh. Ditto $shard_path. If you want those values interpreted/expanded remotely, you need to escape the $, eg \\$path.

Here's a very thorough treatment on this subject .

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