Linux

如何在 bash 腳本中的 SSH 中執行多行程式碼

  • January 24, 2019

我想執行下面的程式碼,但它在 vi 中用紅色突出顯示程式碼中的錯誤。在sudo ssh -t root@$ip << EOF line 之後出現錯誤。我在哪裡編寫錯誤的腳本?

#!/bin/bash
cassandra_home=$(python -c "import json; print \",\".join(json.load(open('${repair.json}','r'))[\"cassandra_home\"])")
iplist[@]=$(python -c "import json; print \",\".join(json.load(open('${repair.json}','r'))[\"iplist\"])")
for ip in ${iplist[@]}
do
 sudo ssh -t root@$ip &lt;&lt; EOF
   for ip in ${iplist[@]} 
   do
     echo Checking $ip for ongoing repairs
     ${cassandra_home}nodetool -h $ip tpstats | grep Repair#
     response=$?
     if [ $response -eq 0 ]; then
       repair_ongoing=true
       echo "Ongoing repair on $ip"
     fi
   done 
   if ! [ $repair_ongoing ]; then
     ## echo "Taking a snapshot."
     ## ${cassandra_home}bin/nodetool -h $ip snapshot
     echo "Starting repair on $ip"
     start=$(date +%s)
     ${cassandra_home}bin/nodetool -h $ip repair -pr -inc -local metadata
     sleep 3
     ${cassandra_home}bin/nodetool -h $ip cleanup metadata 
     end=$(date +%s)
     #echo "ks.tab,st,et,last run,status"&gt;&gt;repair_status.csv
     echo "Repair and cleanup completed for metadata in $((end - start)) seconds"
   fi
   exit 0
 EOF
done           

使用https://www.shellcheck.net/(有一個 vim 外掛)它會告訴你

Line 18:
 EOF
^-- SC1039: Remove indentation before end token (or use &lt;&lt;- and indent with tabs).

然後繼續列出許多其他問題。

您正在嘗試將值數組儲存在iplist[@]但作為靜態聲明…

嘗試如下:

#!/bin/bash
cassandra_home=(`python -c "import json; print \",\".join(json.load(open('${repair.json}','r'))[\"cassandra_home\"])"`)
iplist[@]=(`python -c "import json; print \",\".join(json.load(open('${repair.json}','r'))[\"iplist\"])`)
for ip in ${iplist[@]}
do
 sudo ssh -t root@$ip "
   for ip in ${iplist[@]} 
   do
     echo Checking $ip for ongoing repairs
     ${cassandra_home}nodetool -h $ip tpstats | grep Repair#
     response=$?
     if [ $response -eq 0 ]; then
       repair_ongoing=true
       echo \"Ongoing repair on $ip\"
     fi
   done 
   if ! [ $repair_ongoing ]; then
     ## echo \"Taking a snapshot.\"
     ## ${cassandra_home}bin/nodetool -h $ip snapshot
     echo \"Starting repair on $ip\"
     start=`date +%s`
     ${cassandra_home}bin/nodetool -h $ip repair -pr -inc -local metadata
     sleep 3
     ${cassandra_home}bin/nodetool -h $ip cleanup metadata 
     end=`date +%s`
     #echo \"ks.tab,st,et,last run,status\"&gt;&gt;repair_status.csv
     echo \"Repair and cleanup completed for metadata in $end - $start seconds\"
   fi
   exit 0"

done   

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