1

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?

0

2 Answers 2

7

$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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I understand what I did wrong now. Also the option being a instead of h was a mistake on my part; they were all supposed to be h.
0
#!/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.

1 Comment

The correct construct is "$@" unless the OP specifically wants to wreck the quoting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.