Récupérer le repertoire parent d’un batch en MS-DOS / Retrieve the parent directory in a MS-DOS batch

Vous vous êtes déjà demandé comment récupérer le repertoire parent d’un batch en MS-DOS et constatez que %cd% ne marchait pas correctement car il envoie votre repertoire courant et pas le répertoire du script (Faites un test en créant un fichier test.cmd contenant le texte echo %cd% et appelez le depuis un autre repertoire/disque en utilisant son chemin absolu. Cela renverra votre propre emplacement). La solution est le code suivant :


SET CURRENT_DIR=%~dp0 
SET CURRENT_DIR=%CURRENT_DIR:~0,-1%

La première ligne récupère le chemin complet du répertoire avec le \ de fin. La seconde ligne supprime ce \ de fin.

La preuve par l’exemple :

whereami

Plus d’informations ici.


You ever wondered how to recover the directory parent in a MS-DOS batch and see that %cd% does not work correctly because it sends your current directory and not the directory of the script (do a test by creating a file test.cmd containing the echo %cd% text and run it from another directory/disk using its absolute path. This will return your own location). The solution is the following code:


SET CURRENT_DIR=%~dp0 
SET CURRENT_DIR=%CURRENT_DIR:~0,-1%

 

The first line retrieves the full path of the directory with the ending \. The second line removes this ending \.

The proof:

whereami

Further details here.

Laurent.

Feel free to share:)