我在 bash 腳本中有以下代碼:
remote_home=/home/folder
dump_file=$remote_home/my_database_`date %F_%X`.sql
aws_pem=$HOME/my_key.pem
aws_host=user@host
local_folder=$HOME/db_bk
pwd_stg=xxxxxxxxxxxxxxxx
pwd_prod=xxxxxxxxxxxxxxx
ssh -i $aws_pem $aws_host << EOF
mysqldump --column-statistics=0 --result-file=$dump_file -u user -p$pwd_prod -h $db_to_bk my_database
mysql -u user -p$pwd_prod -h $db_to_bk -N -e 'SHOW TABLES from my_database' > $remote_home/test.txt
sh -c 'cat test.txt | while read i ; do mysql -u user -p$pwd_prod -h $db_to_bk -D my_database --tee=$remote_home/rows.txt -e "SELECT COUNT(*) as $i FROM $i" ; done'
EOF
我的回圈 while 不起作用,因為“i”變數變空了。有人可以幫幫我嗎?我想了解在這種情況下如何處理資料。
uj5u.com熱心網友回復:
本地 shell 正在“擴展” $variablehere-document 中的所有參考,但是您希望將 AIUI$i傳遞到遠程 shell 并在那里擴展。為此,請轉義(使用反斜杠)$您不希望本地 shell 擴展的字符。我認為它看起來像這樣:
ssh -i $aws_pem $aws_host << EOF
mysqldump --column-statistics=0 --result-file=$dump_file -u user -p$pwd_prod -h $db_to_bk my_database
mysql -u user -p$pwd_prod -h $db_to_bk -N -e 'SHOW TABLES from my_database' > $remote_home/test.txt
sh -c 'cat test.txt | while read i ; do mysql -u user -p$pwd_prod -h $db_to_bk -D my_database --tee=$remote_home/rows.txt -e "SELECT COUNT(*) as \$i FROM \$i" ; done'
EOF
ssh -i $aws_pem $aws_host您可以通過將命令替換為 just 來測驗這一點cat,因此它會列印 here-document,因為它將被傳遞給ssh命令(即在本地 shell 完成決議和擴展之后,但在遠程 shell 完成之前)。您應該看到大多數變數被它們的值替換(因為這些變數必須在本地發生,這些變數是在其中定義的)但是按$i字面意思傳遞,以便遠程 shell 可以擴展它。
順便說一句,你應該雙引號幾乎所有的變數參考(例如ssh -i "$aws_pem" "$aws_host"),以防止奇怪的決議問題;shellcheck.net會為本地命令指出這一點(以及其他一些潛在問題),但您也應該為遠程命令修復它(除了$i,因為它已經作為命令的一部分被雙引號括起來SELECT)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/468645.html
