What happens if I call a bash script function with the name of a binary file located in PATH?

Suppose I write a function in a bash script, with the name of an available binary, say pwd:

function pwd(){ echo '/' } 

Well, this seems a little strange, but the question arises: what happens if I write commands in my script:

 cd /usr pwd 

Which pwd will be used? Also, how can I get another to use?

+6
source share
3 answers

Your function will be called because it hides the built-in pwd .

To make a command execute, use command builtin:

 command pwd 

From the 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. 
+8
source

The function will take precedence. You can easily check it using type pwd .

Given that pwd is built-in, you can achieve a real implementation with builtin pwd .

If you want to get the executable from your system, you can refer to its path, for example. using $(which pwd) .

+5
source

Functions take precedence over finding a path. Use the full path to avoid using the function. The builtin keyword provides a similar tool for Bash's built-in keywords ( echo , cd , etc.)

0
source

Source: https://habr.com/ru/post/895660/


All Articles