Write a script:
1, create a function, can accept two parameters:
1) The first parameter is a URL, you can download the file, the second parameter is a directory, that is, the location of the download after the save;
2) If the user-given directory does not exist, the user is prompted to create it, or if it is created, the function returns a 51 error value to the calling script;
3) If the given directory exists, then download the file; Download command after the execution of the test file download success or not; If successful, return 0 to the calling script, otherwise, return 52 to the calling script;
Topics from 51cto forum posts, reference to the answer of the great God, and then their own perfect to make, we have a better way to write it out.
#!/bin/bash#writen by mofansheng @2015-08-10url=$1dir=$2download () { 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 " " fi else return "Wuyi" fi else wget $url &>/dev/null if [ $? -ne 0 ];then return " " fi fi}download $url $direcho $?
A lot of if judgment a bit confused;
Validation results:
Directory exists, then return 0, download the file into the existing directory;
[[Email protected] ~]# sh 1.sh http://www.baidu.com/index.php yong0[[email protected] ~]# ls yong/index.php
The directory does not exist, prompts whether to create, select N is not created, then returns 51;
[[Email protected] ~]# sh 1.sh http://www.baidu.com/index.php fanfan No such file or Directory,create now? (y/n) n51
The directory does not exist, prompts whether to create, select Y to Create, and download the file into the newly created directory;
[[Email protected] ~]# sh 1.sh http://www.baidu.com/index.php fanfan No such file or Directory,create now? (y/n) y0[[email protected] ~]# ls fan/index.php
The download file is unsuccessful and returns 52;
[Email protected] ~]# sh 1.sh http://www.baidu.com/xxxx.php fan52
This article is from the "Model Student's Learning blog" blog, please be sure to keep this source http://mofansheng.blog.51cto.com/8792265/1683714
Shell script: Create function and specify directory to download