Linux – How to invoke a function in bash shell script

bashlinuxshell

I just wonder the distinction calling the function between $(one_function) and one_function in bash shell script.

When I set the variable PS1 in ~/.bashrc, I can't invoke the function by one_func
ex:

export PS1="\n\[\e[31m\] \$(one_func)  # it works 

export PS1="\n\[\e[31m\] one_func      # it doesn't work

Best Answer

Contrary to how variables are accessed, functions are invoked by name without preceding the name with a '$'.

You might be confused about how on the command line, you can define a function and invoke that function by name, but in your PS1 you had to put the command in parenthesis preceded by a '\$'. Enclosing the function name in '$(' and ')' causes the entire '$(function)' to be replaced by whatever the standard output of that function is. Putting the backslash in front of that causes your shell to evaluate/run that function each time it wants to output $PS1. If you had left off the backslash, the function would have been called just once, when you first defined PS1, and whatever the output of the function was that first time, would forever be in your PS1 prompt from then on.

Related Question