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

时间:2015-05-15 02:45:00

标签: bash unix variable-assignment

我在尝试为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

该脚本的目的是运行带有线程或进程运行它的选项的ac文件,因此它要求您使用的进程/线程数,如果您想使用进程或线程和输入和输出文件。

1 个答案:

答案 0 :(得分:0)

我认为你的目标是这样:

#!/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