相关疑难解决方法(0)

你如何使用getopts?

bash脚本中使用getopts的最简单,最直接的方法是什么.

如果我有一个名为脚本:MyScript可CAN取的参数:-p -r -s -x

if argument x then exit
if argument p then echo "port 10"
if argument s then add 2+2
if argument r then echo env 
Run Code Online (Sandbox Code Playgroud)

这是一个假设的脚本,但我想看一个如何做到这一点的例子.

bash getopts

3
推荐指数
1
解决办法
2657
查看次数

为什么getopt在我的mac os中运行不正常?

在bash:我输入命令:

getopt -l name,data -- --namd
Run Code Online (Sandbox Code Playgroud)

而输出是

-- name,pp -- --namd
Run Code Online (Sandbox Code Playgroud)

输入:

getopt -l name,data -- --name
Run Code Online (Sandbox Code Playgroud)

输出其他

-- name,pp -- --name
Run Code Online (Sandbox Code Playgroud)

我输入时为什么不告诉我错误getopt -l name,data -- --namd

shell getopt

2
推荐指数
1
解决办法
4291
查看次数

从Bash中的自定义选项读取参数

我正在尝试创建一个bash脚本并接受2个选项

  • bePort和fePort

因为这正在工作

while getopts ":a:b:" opt; do
  case $opt in
    a)
      echo "-a was triggered!, Parameter: $OPTARG" >&2
      ;;
    b)
      echo "-b was triggered!, Parameter: $OPTARG" >&2
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
  esac
done
Run Code Online (Sandbox Code Playgroud)

我跑

bash test.sh -a aaa -b bbb

我有

-a was triggered!, Parameter: aaa
-b was triggered!, Parameter: bbb
Run Code Online (Sandbox Code Playgroud)

所以,我尝试了这个

while getopts ":fe:be:" opt; do
  case $opt in
    fe)
      echo "-fe was triggered!, Parameter: $OPTARG" >&2
      ;;
    be)
      echo "-be was …
Run Code Online (Sandbox Code Playgroud)

unix bash shell

2
推荐指数
1
解决办法
106
查看次数

按索引访问shell脚本参数

当你进入shell编程时,我确信这是一个明智的选择.不幸的是我不是,而且我很难过......

我需要验证传递给shell脚本的参数.我还想存储在数组中传递的所有参数,因为我稍后需要进一步分离.

我有一个参数"-o",必须后跟0或1.因此,我想检查以下参数是否有效.这是我试过的:

# Loop over all arguments
for i in "$@"
do
    # Check if there is a "-" as first character,
    # if so: it's a parameter
    str="$i"
    minus=${str:0:1}

    # Special case: -o is followed by 0 or 1
    # this parameter needs to be added, too
    if [ "$str" == "-o" ]
    then
        newIdx=`echo $((i+1))`   # <-- problem here: how can I access the script param by a generated index?
        par="$($newIdx)"

        if [[ "$par" != "0" || …
Run Code Online (Sandbox Code Playgroud)

parameters bash shell scripting

1
推荐指数
1
解决办法
3755
查看次数

使用长选项正确使用 bash getopts

我写了下面的代码来使用长选项和getopts,但它不起作用(参数对变量的值没有影响)。什么是正确的语法?

while getopts "c:(mode)d:(file1)e:(file2)" opt; do
  case $opt in
  -c|--mode)
      mode=$OPTARG
      ;;  
  -d|--file1)
      file1=$OPTARG
      ;;  
  -e|--file2)
      file2=$OPTARG
      ;;  
  esac
done
Run Code Online (Sandbox Code Playgroud)

bash getopts

1
推荐指数
1
解决办法
3251
查看次数

标签 统计

bash ×4

shell ×3

getopts ×2

getopt ×1

parameters ×1

scripting ×1

unix ×1