美文网首页
Shell中获取参数

Shell中获取参数

作者: ZackJiang | 来源:发表于2019-09-26 14:21 被阅读0次

Shell中获取参数

如果只需要传入参数,基本上可以使用$n来取参数,注意n是从1开始的整数

$0 指向的是脚本的名字

$ cat myscript
#!/bin/bash
echo "First arg: $1"
echo "Second arg: $2"
$ ./myscript hello world
First arg: hello
Second arg: world

但是有时需要使用Option来解析参数,并打印帮助信息,下面给出一个简单的例子

#!/bin/bash

helpFunction()
{
   echo ""
   echo "Usage: $0 -a parameterA -b parameterB -c parameterC"
   echo -e "\t-a Description of what is parameterA"
   echo -e "\t-b Description of what is parameterB"
   echo -e "\t-c Description of what is parameterC"
   exit 1 # Exit script after printing help
}

while getopts "a:b:c:" opt
do
   case "$opt" in
      a ) parameterA="$OPTARG" ;;
      b ) parameterB="$OPTARG" ;;
      c ) parameterC="$OPTARG" ;;
      ? ) helpFunction ;; # Print helpFunction in case parameter is non-existent
   esac
done

# Print helpFunction in case parameters are empty
if [ -z "$parameterA" ] || [ -z "$parameterB" ] || [ -z "$parameterC" ]
then
   echo "Some or all of the parameters are empty";
   helpFunction
fi

# Begin script in case all parameters are correct
echo "$parameterA"
echo "$parameterB"
echo "$parameterC"

相关文章

  • Shell中获取参数

    Shell中获取参数 如果只需要传入参数,基本上可以使用$n来取参数,注意n是从1开始的整数 $0 指向的是脚本的...

  • shell向python传参数

    shell向python传参数 1 直接从命令框中获取参数 想要在shell中调用python脚本时实现 利用 s...

  • shell 脚本参数解析之 getopt getopts

    本文转自:https://www.bbsmax.com/A/ZOJPrxqldv/ 一、说明 shell中获取参数...

  • 构建GOCD Pipeline你应该知道的Shell脚本知识

    Shell基础 Shell脚本开始 function 获取参数 获取function 返回值。方法体内通过echo...

  • 工具 | Shell 教程笔记 (2)

    Shell 传递参数 在执行 Shell 脚本时,向脚本传递参数,脚本内获取参数的格式为:$n 其他用法: 参考 ...

  • shell(三)

    Shell 传递参数 我们可以在执行 Shell 脚本时,向脚本传递参数,脚本内获取参数的格式为:$n。n 代表一...

  • Shell 传递参数

    Shell 传递参数 我们可以在执行 Shell 脚本时,向脚本传递参数,脚本内获取参数的格式为:$n。n代表一个...

  • 学习Shell - 传递参数

    Shell传递参数 我们可以在执行 Shell 脚本时,向脚本传递参数,脚本内获取参数的格式为:$n。n 代表一个...

  • shell传递参数

    Shell 传递参数 我们可以在执行 Shell 脚本时,向脚本传递参数,脚本内获取参数的格式为:$n。n代表一个...

  • Shell 传递参数

    Shell 传递参数我们可以在执行 Shell 脚本时,向脚本传递参数,脚本内获取参数的格式为:$n。n 代表一个...

网友评论

      本文标题:Shell中获取参数

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