简体   繁体   中英

Passing variables in remote ssh command in shell script

Right now I have this file so far...

#!/usr/bin/env bash

DIRECTORY=$1

ssh root@example.com "$( cat <<'EOT'
cd /web/$DIRECTORY || exit
pwd
unset GIT_DIR
git log --oneline -n 10 --decorate
git branch
EOT
)";

Why does the pwd just print out "/web/"? It doesn't actually seem to be using my variable. Then all the git commands throw errors about being in the web directory.

If I have it echo $DIRECTORY out before ssh-ing, it echos out my variable, but refuses to pass it through to the ssh command?

This happens because you quote the here doc delimiter. Here's POSIX :

If any character in word is quoted, the delimiter is formed by performing quote removal on word, and the here-document lines will not be expanded . Otherwise, the delimiter is the word itself.

And here's an example:

#!/bin/bash
var=42

cat << 'end'
With quotes: $var and \$var
end

cat << end
Without quotes: $var and \$var
end

When executed:

With quotes: $var and \$var
Without quotes: 42 and $var

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