[Linux]Shell脚本接收参数并判断参数args是否输入校验

2021-08-23 3153点热度 0人点赞 0条评论

写好的Shell脚本,需要执行的时候,从外部传入参数,例如sh xxx.sh /path/to/file,执行xxx.sh脚本,接收外部传入的文件路径作为参数

实现

在脚本里,可以使用$1作为脚本的参数,如果有多个参数,传入的时候,用空格隔开,脚本内部用$1 $2……来区分,例如:sh xxx.sh /path/to/file1 /path/to/file2

另外,我们还可以使用如下代码,对参数做是否输入的校验:

  • 如果没有输入参数,就提示本脚本的使用说明
#!/bin/bash

if [ -z "$1" ]; then
    echo "usage: sh xxx.sh /path/to/file"
    exit
fi
  • 两个参数检查
#!/bin/bash

if [[ -z $1 && -z $2 ]]; then
    echo "usage: sh xxx.sh arg1 arg2"
    exit
fi

 

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论