需求說明
最近在AIX上做開發,開發機器在office網段,測試機器在lab網段,不能互相通訊,只能通過特定的ftp來傳文件。
每次上傳的機器都要做:登錄ftp,進入我的目錄,上傳;下載的機器都要做:登錄ftp,進入我的目錄,下載。以上動作每天都要做幾十次,很蛋疼。
這個shell腳本的功能就是完成這些功能:登錄ftp,進入我的目錄,上傳/下載某些文件。要傳入一個參數,這個參數如果是“get”,那就從ftp下載;如果是“put”,那就上傳到ftp。
因為從來沒有用過shell腳本,所以將一些關鍵點記錄下來,以便今后揣摩。
腳本代碼
主要流程:
- 判斷是不是有一個參數,參數是不是“get”或者“put”,不滿足的話就打印錯誤並退出。
- 將登陸ftp,進入目錄的動作寫入一個臨時的shell腳本。
- 如果參數是“get”,將下載所有文件的代碼寫入臨時腳本。如果參數是“put”,取到本地文件夾的所有文件,逐個將上傳代碼加入臨時腳本。
- 將斷開ftp的代碼寫入臨時文件。
- 執行臨時文件並刪除。
1 #!/bin/sh 2 3 if [ $# -ne 1 ] ; then 4 echo "parameter error" 5 exit 6 else 7 if [ $1 != "get" ] && [ $1 != "post" ] ; then 8 echo "parameter error" 9 exit 10 fi 11 fi 12 13 ftp_host="10.204.16.2" 14 ftp_user="test" 15 ftp_password="testtest" 16 folder_local="/home/smld/sync" 17 folder_remote="/home/smid/frank/sync" 18 temp_shell="sync_temp.sh" 19 20 cat > $temp_shell << EOF 21 ftp -v -n << ! 22 open $ftp_host 23 user $ftp_user $ftp_password 24 lcd $folder_local 25 cd $folder_remote 26 bin 27 prompt off 28 EOF 29 30 if [ $1 = "get" ]; then 31 echo "add mget * into $temp_shell" 32 echo "mget *" >> $temp_shell 33 elif [ $1 = "put" ]; then 34 for i in `ls $folder_local`; do 35 echo "add put $i into $temp_shell" 36 echo "put $i" >> $temp_shell 37 done 38 fi 39 40 cat >> $temp_shell << EOF 41 quit 42 ! 43 EOF 44 45 chmod 777 $temp_shell 46 echo "execute $temp_shell" 47 ./$temp_shell 48 rm $temp_shell
代碼詳解
第1行
#!/bin/sh,用來指定shell的程序路徑。
3-11行
if條件語句:
if [條件]; then
elif [條件]; then
else
fi
判斷數字是否相等:-eq(equal)-ne(not equal),其他大於小於也類似。
判斷字符串時候相等:=(等於)!=(不等於)
條件直接的與或:&&(與)||(或) -a(and)-o(or)
傳入參數用$1 $2 ... $9表示 ,$0表示腳本名,$@表示所有參數的數組(可以超過9個),$#表示參數個數。
13-18行
設置一些參數,參數賦值
20-28行
把一段內容輸入到文件:cat 內容 > 文件名,用>會清空文件原來的內容,用>>會在文件后面追加。echo也有這樣的功能。
將多行內容作為命令的輸入,EOF只是一個標志,像21行換成!作用也是一樣的:
命令 << EOF
內容段
EOF
ftp相關命令:
- 選項-v:顯示詳細信息
- 選項-n:關閉自動登錄(open之后不會彈出提示輸入用戶名密碼)
- 連接某個ftp:open 主機名
- 登錄:user 用戶名 密碼
- 指定本地目錄:lcd 目錄
- 轉成二進制傳輸:bin
- 關閉主動模式(mget的時候不會逐個文件詢問y/n):prompt off
30-38行
for循環:
for i in 集合; do
done
集合可以使用命令的結果,用``把命令包起來,例如:`ls $folder_local`