0
#!/bin/bash function main { [ -z "$1" ] && { getPID "$@"; } || $1 } getPID() { a=$1 b='service' if [[ $a == 'contains' ]]; then PID=$(pgrep -f $b) elif [[ $a == 'exact' ]]; then PID=$(pgrep -x $b) fi echo "$PID" } main "$@" 

command : I am running for calling the function : ./script.sh getPID contains

Output : it prints blank and value of variable a is blank

13
  • 1
    cut-n-paste your code (along with appropriate shebang) into shellcheck.net and make the recommended change(s); if you still have issues after making the shellcheck recommended changes then come back and update the question to show a) your latest/updated code and b) the new issue(s) you're experiencing Commented Dec 15, 2023 at 18:49
  • check your script with shellcheck.net. Commented Dec 15, 2023 at 18:49
  • 1
    When I copy/paste the current code from your question into shellcheck.net it still reports issues. Commented Dec 15, 2023 at 19:06
  • 1
    (and as others have said, you still have bugs that shellcheck would catch; please fix all of them). Commented Dec 15, 2023 at 19:15
  • 1
    @NitinAlety what you're trying to do is a bad idea that will tightly couple the code inside this script to any calls of your script (whether manually or from other scripts) and introduces some unnecessary complexity in implementing your script, see mywiki.wooledge.org/BashFAQ/050 for information on storing code in a variable in general. There are no existing Unix utilities that expose an interface where a user can call a function defined within the utility by name, for good reason. Commented Dec 15, 2023 at 19:22

1 Answer 1

2

When you invoke $1 within main (when $1 contains the string getPID), that just calls getPID with no arguments.

To pass additional arguments through to getPID, you should use "$@" instead of $1.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.