题目:老男孩教育每日一题-2017年5月3日-写一个脚本:创建一个函数,能接受两个参数

题目要求

1)第一个参数为URL,即可下载的文件;第二个参数为目录,即下载后保存的位置;
2)如果用户给的目录不存在,则提示用户是否创建;如果创建就继续执行,否则,函数返回一个51的错误值给调用脚本;
3)如果给的目录存在,则下载文件;下载命令执行结束后测试文件下载成功与否;如果成功,则返回0给调用脚本,否则,返回52给调用脚本;

参考答案

[root@oldboyedu scripts]# cat downfile.sh#!/bin/bashurl=$1dir=$2download(){    if [ ! -e $dir ];then     	read -p "$dir No such file or directory,create?(y/n)" answer    	if [ "$answer" == "y" ];then    		mkdir -p $dir    		cd $dir    		wget $url 1 >/dev/null 2>&1    		if [ $? -ne 0 ]; then    			return "52"    		fi        else    		return "51"    	fi    fi    }download $url $direcho $?

网友回答

向日葵-架构师交流群

#!/bin/shif [ ! -d $2 ];thenecho "Directory does not exist.";exit 51fiwget -O $2${1##*/} $1if [ $? -ne 0 ];thenecho "Failed to download file."exit 52fi

今天是每日一题陪伴大家的第41天期待你的进步

对于题目和答案的任何疑问,请在博客评论区留言
往期题目索引