手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Shell脚本:创建函数并指定目录进行下载

[日期:2015-08-22] 来源:Linux社区  作者:mofansheng [字体:大 中 小]

写一个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

本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-08/122109.htm

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款