Bash

SSH 後帶引號的多個命令

  • November 14, 2016

我有一個伺服器,我必須使用許多命令通過 ssh 進入,這些命令的特點是使用變數賦值,因此有很多引號。如果我們考慮腳本:

ssh user@host  "kinit -k -t /path/to/dir/`whoami`.`hostname -s`.keytab `whoami`/`hostname -f`@host ;

set -x

touch health_check.log ;

echo \"Starting HDFS health check\" > health_check.log ;
echo \"/path/to\" >> health_check.log ;

hdfs dfs -du -h /path/to &>> health_check.log ;

echo \"**************************************************************************
/path/to/dir\" >> health_check.log ;

hdfs dfs -du -h /path/to/dir &>> health_check.log ;

subject=\"HDFS Health Check\" ;
from=\"noreply@example.com\" ;
recipients=\"user@email.com\" ;
mail=\"subject:$subject\nfrom:$from\nContent-Type: text/html\nMIME-Version: 1.0\n\n$(cat health_check.log)\" ;



echo -e $mail | sendmail \"$recipients\" ;

set +x
rm health_check.log
"

當我執行腳本時,我得到了這個調試輸出:

++ subject='HDFS Health Check'
++ from=noreply@example.com
++ recipients=user@email.com
++ mail='subject:\nfrom:\nContent-Type: text/html\nMIME-Version: 1.0\n\nStarting HDFS health check /data/gftocon'
++ echo -e
++ sendmail ''

注意我的變數應該在哪裡的空字元串。為什麼轉義引號不起作用?

那是因為腳本是雙引號的:你的 shell在啟動 ssh 命令之前替換了變數。您可以添加一些額外的反斜杠,或使用引用的 heredoc,如下所示:

ssh user@host  <<'END_COMMANDS'
# ...............^............^ these quotes make the whole document single-quoted
kinit -k -t /path/to/dir/`whoami`.`hostname -s`.keytab `whoami`/`hostname -f`@host
set -x
echo "Starting HDFS health check" > health_check.log 
echo "/path/to" >> health_check.log 
hdfs dfs -du -h /path/to &>> health_check.log 
echo "**************************************************************************
/path/to/dir" >> health_check.log 
hdfs dfs -du -h /path/to/dir &>> health_check.log 

subject="HDFS Health Check" 
from="noreply@example.com" 
recipients="user@email.com" 

headers="subject:$subject
from:$from
Content-Type: text/html
MIME-Version: 1.0"

{ echo "$headers"; echo; cat health_check.log; } | sendmail "$recipients" 

set +x
rm health_check.log
END_COMMANDS

我認為這更容易維護。

引用自:https://unix.stackexchange.com/questions/323200