Search code examples
bashargumentsgetopts

Pass text file as argument/variable [bash]


I am trying to pass a text file as a specific argument and print its name and content...

#!/bin/bash

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

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

(for running it: sh myscript.sh -f filelist)

Something is really wrong because even the file name is not appearing! (and curiously, in bash everything goes well, why?).


Solution

  • According @Barmar's answer (thanks!) I forgot the colon with f... but, as I was trying to make this argument optional, this should be after. Based on this other question and @Barmar's point, the "final" code could be like that:

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