How can I invoke a function in bash shell script

4

3

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

sufery

Posted 2010-04-24T20:42:21.277

Reputation: 39

Answers

5

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.

Marnix A. van Ammers

Posted 2010-04-24T20:42:21.277

Reputation: 1 978

1

When you invoke $(one_func), it will execute the function, and return the output. So if you say, for example:

var=$(ls)

it will store the output of the ls command (i.e. the list of files in the current directory) into the variable $var. While the command:

var=ls

will just set the value of $var to "ls".

By the way, calling a function in bash works the same way as executing a command.

petersohn

Posted 2010-04-24T20:42:21.277

Reputation: 2 554

0

Just to add to the above. very useful information... the same idea applies when nesting functions and calling executables...

PS1="# \e[1;30m\u\e[0;37m@\h: \e[1;31m\w\e[31m >\e[1;30m  \t \e[1;33m [ \$(kmg \$(totalfilesize.sh)) ]\e[m\n"

"kmg" is a bash function i've defined, and with this syntax is passed an argument from the output of the "totalfilesize.sh" script

\$(kmg \$(totalfilesize.sh))

If you're curious, totalfilesize computes the size of the files in the current directory, and kmg converts the string (in bytes) to human-readable b, mB, gB, etc.

mralexgray

Posted 2010-04-24T20:42:21.277

Reputation: 668