Suppose I write a function in a bash script, with the name of an available binary, say, pwd:
function pwd(){
echo '/'
}
Alright, that seems a bit weird, but the question is: what will happen if further in my script I write the commands:
cd /usr
pwd
What pwd
will be used? Also, how can I force the use of the other one?
$# is the number of positional parameters passed to the script, shell, or shell function. This is because, while a shell function is running, the positional parameters are temporarily replaced with the arguments to the function. This lets functions accept and use their own positional parameters.
Complete answer: Functions in bash are not first-class objects, therefore there can be no such thing as an anonymous function in bash.
Example of command substitution using $() in Linux: Again, $() is a command substitution which means that it “reassigns the output of a command or even multiple commands; it literally plugs the command output into another context” (Source).
There are two ways to implement Bash functions: Inside a shell script, where the function definition must be before any calls on the function. Alongside other bash alias commands and directly in the terminal as a command.
Your function will get called because it hides the pwd
builtin.
To force the command to be executed, use the command
builtin:
command pwd
From bash manual:
command [-pVv] command [arg ...]
Run command with args suppressing the normal shell function
lookup. Only builtin commands or commands found in the PATH are
executed. If the -p option is given, the search for command is
performed using a default value for PATH that is guaranteed to
find all of the standard utilities. If either the -V or -v
option is supplied, a description of command is printed. The -v
option causes a single word indicating the command or file name
used to invoke command to be displayed; the -V option produces a
more verbose description. If the -V or -v option is supplied,
the exit status is 0 if command was found, and 1 if not. If
neither option is supplied and an error occurred or command can-
not be found, the exit status is 127. Otherwise, the exit sta-
tus of the command builtin is the exit status of command.
Function will have precedence. You can check it easily using type pwd
.
Considering that pwd
is a builtin, you can reach the real implementation using builtin pwd
.
If you want to actually get the executable from your system, you can refer to its path, e.g. using $(which pwd)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With