¿Cómo obtener la ruta del script por lotes en Windows?


Sé que %0 contiene la ruta completa del script por lotes, por ejemplo, c:\path\to\my\file\abc.bat

Yo path sería igual a c:\path\to\my\file

¿Cómo podría lograr eso ?

Author: Daniel Earwicker, 2010-09-30

5 answers

%~dp0 será el directorio. Aquí hay documentación sobre todos los modificadores de ruta. Cosas divertidas: -)

Para eliminar la barra invertida final, puede usar la sintaxis de subcadenas :n,m, así:

SET mypath=%~dp0
echo %mypath:~0,-1%

No creo que haya una manera de combinar la sintaxis %0 con la sintaxis :~n,m, desafortunadamente.

 425
Author: Dean Harding,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-18 04:39:58

%~dp0 puede ser un camino relativo. Para convertirlo en una ruta completa, intente algo como esto:

pushd %~dp0
set script_dir=%CD%
popd
 16
Author: Arnaud,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-31 14:54:02

Puede usar el siguiente script para obtener la ruta sin " \ "

for %%i in ("%~dp0.") do SET "mypath=%%~fi"
 6
Author: duan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-01 08:35:15

Esa sería la variable %CD%.

@echo off
echo %CD%

%CD% devuelve el directorio actual en el que se encuentra el script por lotes.

 -6
Author: Ruel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-30 03:52:15

Estoy trabajando en una máquina con Windows 7 y he terminado usando las líneas a continuación para obtener la ruta de carpeta absoluta para mi script bash.

Llegué a esta solución después de mirar http://www.linuxjournal.com/content/bash-parameter-expansion.

#Get the full aboslute filename.
filename=$0
#Remove everything after \. An extra \ seems to be necessary to escape something...
folder="${filename%\\*}"
#Echo...
echo $filename
echo $folder
 -7
Author: Jonas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-03 09:11:46