linux函数怎么新建立目录,shell脚本:创建函数并指定目录进行下载

写一个脚本:

1、创建一个函数,能接受两个参数:

1)第一个参数为URL,即可下载的文件;第二个参数为目录,即下载后保存的位置;

2)如果用户给的目录不存在,则提示用户是否创建;如果创建就继续执行,否则,函数返回一个51的错误值给调用脚本;

3)如果给的目录存在,则下载文件;下载命令执行结束后测试文件下载成功与否;如果成功,则返回0给调用脚本,否则,返回52给调用脚本;

题目来源于51cto论坛帖子,参考大神的答案,然后自己完善做出来了,大家有更优秀的方法也不妨写出来。#!/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.baidu.com/index.php yong

0

[root@localhost ~]# ls yong/

index.php

目录不存在,提示是否要创建,选n不创建,则返回51;[root@localhost ~]# sh 1.sh http://www.baidu.com/index.php fan

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

51

目录不存在,提示是否要创建,选y创建,并且下载文件到新创建的目录里;[root@localhost ~]# sh 1.sh http://www.baidu.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.baidu.com/xxxx.php

fan52

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值