5

I have defined a function in bash_profile file.

pse(){
ps -ef|grep $1
}

Now i can call this function from command line. Like

pse kafka

It is working fine as i can see the correct output. But when i am trying to call pse function in an script file, it is showing me "command not found" error. Am i missing something? Are we not allowed to call function defined in bash_profile from shell script? OS : MacOsX Yosemite

4
  • 1
    Did you source your bash_profile after adding the function into the file? source ~/.bash_profile probably. Commented Nov 25, 2015 at 16:18
  • yeah i did that, that's why i can call that function from command line and it is showing correct output Commented Nov 25, 2015 at 16:19
  • You have the source command in the script? Commented Nov 25, 2015 at 16:27
  • 1
    You don't want this function anyway. You want pgrep. Commented Nov 25, 2015 at 17:12

1 Answer 1

4

You can export the function from the parent's shell to make it available in the child processes:

export -f pse

From the manual:

export

export [-fn] [-p] [name[=value]]

Mark each name to be passed to child processes in the environment. If the -f option is supplied, the names refer to shell functions; otherwise the names refer to shell variables. The -n option means to no longer mark each name for export. If no names are supplied, or if the -p option is given, a list of names of all exported variables is displayed. The -p option displays output in a form that may be reused as input. If a variable name is followed by =value, the value of the variable is set to value.

The return status is zero unless an invalid option is supplied, one of the names is not a valid shell variable name, or -f is supplied with a name that is not a shell function.

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

7 Comments

Yeah now it is working. But why ? Isn't doing source ~/.bash_profile is an equivalent operation.
source "includes" (runs) the function only in the current shell. export makes it available in all child processes. So you need both here. Or you can directly source it in your script.
.bash_profile is only sourced by interactive shells; scripts are executed by non-interactive shells.
@P.P. how would you source it inside the script? I tried doing this with my function using source functionName but when running the script it errors
@GrayedFox source takes a filename. So, if you defined functionName in my_utils.sh then you can do: source my_utils.sh.
|

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.