美文网首页
452. 【Unix/Linux 系统管理】命令行参数与函数

452. 【Unix/Linux 系统管理】命令行参数与函数

作者: 七镜 | 来源:发表于2022-10-09 21:42 被阅读0次

脚本的命令行参数会成为名字为数字的变量。$1 是第一个命令行参数,$2 是第二个,依次类推。$0 是所调用的脚本名。

#!/bin/bash
#Program:
#       show usage && test argument
#History:
#2022/10/08     junfenghe.cloud@qq.com  version:0.0.1
path=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export path

show_usage() {

    echo "Usage: $0 source_dir dest_dir" 1>&2
    
    exit 1

}

# Main program starts here

if [ $# -ne 2 ]; then

    show_usage

else # There are two arguments
   
    if [ -d $1 ]; then

        source_dir=$1

    else

        echo 'Invalid source directory' 1>&2

        show_usage

    fi
    
    if [ -d $2 ]; then
    
        dest_dir=$2

    else

        echo 'Invalid destination directory' 1>&2

        show_usage

    fi

fi

echo "Source directory is ${source_dir}"
echo "Destination directory is ${dest_dir}"

exit 0

如果调用脚本时不带参数或者参数不正确,该脚本会输出一段简短用法说明,提醒用户使用方法。上例中的脚本接受两个参数并验证其均为目录,然后显示出来。如果参数无效,那么脚本在输出用法说明后使用非 0 的返回码退出。如果调用这个脚本的程序检查该返回码,就会知道脚本执行失败。

相关文章

网友评论

      本文标题:452. 【Unix/Linux 系统管理】命令行参数与函数

      本文链接:https://www.haomeiwen.com/subject/rrhnartx.html