2014-06-20 29 views
0

當我創建了一個bash腳本來遷移網站和數據庫從一臺服務器到另一個:算法:While循環只執行一次使用rsync

  1. 解析.pgpass文件來創建所有指定的Postgres數據庫的個性化轉儲。
  2. 通過rsync將上述轉儲上傳到另一臺服務器。
  3. 也通過rsync將一堆與每個數據庫相關的文件夾上傳到另一臺服務器。

由於數據庫和文件夾具有相同的名稱,因此腳本可以在知道文件夾名稱的位置時預測文件夾的位置。我面臨的問題是循環只執行一次(只有第一行.pgpass正在完成)。

這是我的腳本,在源服務器來運行:

#!/bin/bash 

# Read each line of the input file, parse args separated by semicolon (:) 
while IFS=: read host port db user pswd ; do 
    # Create the dump. No need to enter the password as we're using .pgpass 
    pg_dump -U $user -h $host -f "$db.sql" $db 
    # Create a dir in the destination server to copy the files into 
    ssh [email protected] mkdir -p webapps/$db/static/media 
    # Copy the dump to the destination server 
    rsync -azhr $db.sql [email protected]:/home/user 
    # Copy the website files and folders to the destination server 
    rsync -azhr --exclude "*.thumbnails*" webapps/$db/static/media/ [email protected]:/home/user/webapps/$db/static/media 
# At this point I expect the script to continue to the next line, but if exits at the first line 
done < $1 

這是.pgpass,文件解析:

localhost:*:db_name1:db_user1:db_pass1 
localhost:*:db_name3:db_user2:db_pass2 
localhost:*:db_name3:db_user3:db_pass3 
# Many more... 

這是我怎麼叫它:

./my_script.sh .pgpass 

此時一切正常。第一個轉儲已創建,並且會與相關的文件和文件夾一起傳輸到目標服務器。問題是腳本在那裏完成,並且不會解析.pgpass的其他行。我已經註釋掉了與rsync相關的所有行(因此腳本僅創建轉儲),並且它正常工作,爲腳本中的每一行執行一次。如何讓腳本在執行rsync後不退出?

順便說一句,我使用基於密鑰的ssh auth來連接服務器,所以腳本完全沒有提示。

回答

2

讓我們問shellcheck

$ shellcheck yourscript 

In yourscript line 4: 
while IFS=: read host port db user pswd ; do 
^-- SC2095: ssh may swallow stdin, preventing this loop from working properly. 

In yourscript line 8: 
    ssh [email protected] mkdir -p webapps/$db/static/media 
    ^-- SC2095: Add < /dev/null to prevent ssh from swallowing stdin. 

而且你去那裏。

+0

非常好!我只是將-n選項傳遞給ssh,它完成了同樣的事情,現在它正在工作。感謝分享shellcheck。 –