Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
share|improve this question

3 Answers 3

up vote 4 down vote accepted

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.

share|improve this answer
1  
+1 for the explanation of the backslash. –  Dennis Williamson Apr 24 '10 at 23:33

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.

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.