歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> Shell腳本:創建函數並指定目錄進行下載

Shell腳本:創建函數並指定目錄進行下載

日期:2017/3/1 9:25:49   编辑:SHELL編程

寫一個Shell腳本:

1、創建一個函數,能接受兩個參數:

1)第一個參數為URL,即可下載的文件;第二個參數為目錄,即下載後保存的位置;

2)如果用戶給的目錄不存在,則提示用戶是否創建;如果創建就繼續執行,否則,函數返回一個51的錯誤值給調用腳本;

3)如果給的目錄存在,則下載文件;下載命令執行結束後測試文件下載成功與否;如果成功,則返回0給調用腳本,否則,返回52給調用腳本;

#!/bin/bash

#writen by mofansheng @2015-08-10

url=$1

dir=$2

download()

{

cd $dir &>/dev/null

if [ $? -ne 0 ]

then

read -p "$dir No such file or directory,create now?(y/n)" answer

if [ "$answer" == "y" ];then

mkdir -p $dir

cd $dir

wget $url &>/dev/null

if [ $? -ne 0 ];then

return "52"

fi

else

return "51"

fi

else

wget $url &>/dev/null

if [ $? -ne 0 ];then

return "52"

fi

fi

}

download $url $dir

echo $?

好多if判斷有點迷糊了;

驗證結果:

目錄存在,則返回0,下載文件到已存在的目錄裡;

[root@localhost ~]# sh 1.sh http://www.linuxidc.com/index.php yong

0

[root@localhost ~]# ls yong/

index.php

目錄不存在,提示是否要創建,選n不創建,則返回51;

[root@localhost ~]# sh 1.sh http://www.linuxidc.com/index.php fan

fan No such file or directory,create now?(y/n)n

51

目錄不存在,提示是否要創建,選y創建,並且下載文件到新創建的目錄裡;

[root@localhost ~]# sh 1.sh http://www.linuxidc.com/index.php fan

fan No such file or directory,create now?(y/n)y

0

[root@localhost ~]# ls fan/

index.php

下載文件不成功,則返回52;

[root@localhost ~]# sh 1.sh http://www.linuxidc.com/xxxx.php

fan52

Copyright © Linux教程網 All Rights Reserved