shinryu333
shinryu333

Reputation: 333

Command line argument not working when passing to a function while using getopts

I've been trying to get some practice in with bash shell scripting but I've been having trouble using the $1 variable to reference the first argument for my script. It's a simple script that takes a file as an argument and prints the name of the file. Here's my script:

#!/bin/bash

function practice() {
  echo "${1}"
}

while getopts "h:" opt; do
  case "$opt" in
  h) practice
     ;;
  esac
done

exit 0

I tried the following command:

./practice.sh -h somefile.txt

For some reason it returns an empty line. Any thoughts?

Upvotes: 1

Views: 2521

Answers (2)

PesaThe
PesaThe

Reputation: 7499

$1 in functions refers to first positional parameter passed to that function, not passed to your script.

Therefore, you have to pass the arguments you want to the function again. You also tell getopts you want to process -h but then you are checking for -a in your case instead:

#!/bin/bash

practice() {
   echo "${1}"
}

while getopts "h:" opt; do
  case "$opt" in
     h) practice "${OPTARG}"
        ;;
  esac
done

Upvotes: 7

NishanthSpShetty
NishanthSpShetty

Reputation: 659

#!/bin/bash

function practice() {
    echo "${1}"
}

 while getopts "h:" opt; do
  case "$opt" in
  a) practice $*
    ;;
  esac
 done

exit 0

pass the command line arguments to the function as above.

Upvotes: 0

Related Questions