Search code examples
linuxbashshellubuntuunix

calling a function from the terminal with arguments rather the whole bash script is not working


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


Solution

  • 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.