将文本文件作为 argument/variable [bash]

Pass text file as argument/variable [bash]

我正在尝试将文本文件作为特定参数传递并打印其名称和内容...

#!/bin/bash

## set input args
while getopts "f" option; do
    case "${option}" in
        f)
          arg3=${OPTARG};;  
      esac
done

## script
echo $arg3
echo $(cat $arg3)

(对于 运行 它:sh myscript.sh -f filelist

真的有问题,因为连文件名都没有出现! (奇怪的是,在 bash 中一切顺利,为什么?)。

根据@Barmar 的回答(谢谢!)我忘记了带有 f 的冒号...但是,当我试图使这个论点 可选 时,这应该之后。基于这个 other question 和@Barmar 的观点,“最终”代码可能是这样的:

#!/bin/bash

## set input args
while getopts ":f" option; do
    case "${option}" in
        f)
          # Check next positional parameter
          eval nextopt=${$OPTIND}
          # existing or starting with dash?
          if [[ -n $nextopt && $nextopt != -* ]] ; then
            OPTIND=$((OPTIND + 1))
            arg3=$nextopt
          else
            echo "Not filelist specified, closing..." && exit
          fi
        ;;
      esac
done

## script
echo $arg3
echo $(cat $arg3)