无法在 bash 中为 case 语句中的变量赋值



我只是在试图将值分配给案例语句中的变量时遇到了一个问题,这是我的代码:

#!/bin/bash
while getopts ":m:n:::" opt; do
  case $opt in
    n)
      echo "-n was triggered, Parameter: $OPTARG " >&2
      case $OPTARG in 
        t)
            echo threads
            r=threads
            ;;
        p)
            echo processes
            r="something"
            ;;
        esac
      ;;
    m)
      echo "-m was triggered, Parameter: $OPTARG" >&2
      ;;
    ?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done
echo $r
echo No thread/processes: $2 P/T: $4 IF: $5  OF: $6

我想稍后使用变量$r,但我不能。当我尝试使用echo(如我的脚本中)打印它时,它不会返回一件事。我一直在努力发现自己的错误,但我做不到。有一个类似的帖子建议在=之前和之后删除空白空间,但是如您所见,我的中没有空白。

这是我运行时从控制台中获得的:

$ ./friendfind -n 2 -m p IN OUT
-n was triggered, Parameter: 2 
-m was triggered, Parameter: p
No thread/processes: 2 P/T: p IF: IN OF: OUT

该脚本的目的是运行一个C文件,并以线程或进程运行该选项,因此它要求使用您要使用的过程/线程数量,如果您想使用过程或线程以及输入和输出文件。

我认为您的目标是这样:

#!/bin/bash
# Print usage message:
usage() {
  echo "Usage: $0 [-n N] [-t|-p] INPUT OUTPUT" >> /dev/stdout
}
# Set default values
n_threads=1  
use_threads=1
while getopts "n:pth" opt; do
  case $opt in
    n) n_threads=$OPTARG;;
    t) use_threads=1;;
    p) use_threads=0;;
    h) usage; exit 0;;
    *) usage; exit 1;;
  esac
done
# Get rid of scanned options
shift $((OPTIND-1))
if (($# != 2)); then usage; exit 1; fi
if ((use_threads)); then
  echo "Using $n_threads threads. IF: $1; OF: $2"
  # ...
else
  echo "Using $n_threads processes. IF: $1; OF: $2"
  # ...
fi

以下是一些示例调用,包括几个错误:

$ ./ff -p foo bar
Using 1 processes. IF: foo; OF: bar
$ ./ff foo bar
Using 1 threads. IF: foo; OF: bar
$ ./ff -n 7 foo bar
Using 7 threads. IF: foo; OF: bar
$ ./ff -n 7 -p foo bar
Using 7 processes. IF: foo; OF: bar
$ ./ff -p -n7 foo bar
Using 7 processes. IF: foo; OF: bar
$ ./ff -q -n7 foo bar
./ff: illegal option -- q
Usage: ./ff [-n N] [-t|-p] INPUT OUTPUT
# Note: The error message here could be more informative.
# Exercise left for the reader
$ ./ff -n 7 foo
Usage: ./ff [-n N] [-t|-p] INPUT OUTPUT

相关内容

  • 没有找到相关文章

最新更新