Supposons que j’écris une fonction dans un script bash, avec le nom d’un binary disponible, par exemple, pwd:
function pwd(){ echo '/' }
Bon, ça semble un peu bizarre, mais la question est: que se passera-t-il si plus loin dans mon script j’écris les commandes:
cd /usr pwd
Quel pwd
sera utilisé? Comment puis-je forcer l’utilisation de l’autre?
Votre fonction sera appelée car elle cache le paramètre intégré pwd
.
Pour forcer l’exécution de la command
, utilisez la command
builtin:
command pwd
De bash manuel:
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.
La fonction aura la priorité. Vous pouvez le vérifier facilement en utilisant le type pwd
.
Considérant que pwd
est une version intégrée, vous pouvez accéder à l’implémentation réelle en utilisant builtin pwd
.
Si vous voulez réellement obtenir l’exécutable de votre système, vous pouvez vous référer à son chemin, par exemple en utilisant $(which pwd)
.
Les fonctions ont priorité sur la recherche de chemin. Utilisez le chemin d’access complet pour éviter d’inhaler la fonction. Le mot-clé builtin
fournit une fonctionnalité similaire pour les mots-clés intégrés de Bash ( echo
, cd
, etc.)