写一个脚本:
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