Windows bat current dir

on October 23, 2011

Here’s a question from a blog reader.

I need to write a batch script file which can traverse to different directories and do some operations on those directories. Once done, I need to come back to the original directory where the batch script started and do some more stuff. I need to get the initial starting directory and save it in a variable. My question is what’s the simple way to get the the directory from batch script.

Below is the answer for this question.

There is a very simple way to get the directory from a batch script file. CD environment variable stores the current directory of a command window session. Just run the command ‘echo %CD%’ and check it yourself.

C:\Users\windmdline>echo The current directory is %CD%
The current directory is C:\Users\wincmdline

How to use the current directory in batch code. append the filename to the current directory Run another bat or exec file from the current working directory..

The Cd command is used to change the directory in the DOS command line. This post talks about getting a directory path in batch programming.

Sometimes, We want to run files in the current directory in batch programming.

%cd% variable in batch file returns current working directory with full path

test.bat file is declared b:\work directory

@echo off
echo %cd%

By running test.bat from the command line, it prints b:\work

This returns the current working directory

@echo off
echo %cd%
echo %~dp0
echo %~dpnx0

Output:

b:\work
b:\work\
b:\work\test.bat

%~dp0 returns the current director structure followed by \

%~dpnx0 returns current directory structure + name of the running batch file.

How to append the filename to the current directory in the Batch file?

It is easy to append a filename in the current directory structure

@echo off
echo %cd%\notes.txt

Output:

b:\work\notes.txt

Also, You can add filenames to the current directory to a variable using the set command

@echo off
set current=%cd%\notes.txt
echo %current%

Output:

b:\work\notes.txt

Run another bat file from the current working directory.

This is a simple batch code to run another batch file from the current working directory.
We can also use .exe files in place of another batch file.

@echo off
cls
Echo Running other.bat
start %cd%/other.bat
exit

The above code does the following things.

  • First, Clear screen using
  • Next, print the string message
  • Next line, open a new window and run the other.bat file located in the current directory
  • Finally, Exit from the command line.

set papka = %cd%
echo %papka%
pause

Выводит путь C:\Windows\system32\
Но ведь BATник я запускаю на рабочем столе.
Как узнать текущий путь?


  • Вопрос задан

  • 12650 просмотров

Именно так и узнавать текущий путь: %CD%
Это не важно где лежит батник, т.к. исполняется не сам батник, а cmd.exe. Т.е. когда вы 2ПКМите на батнике, лежащем на раб.столе запускается команда: cmd.exe /c c:\users\user\Desktop\file.bat
При этом путь где лежит батник никакого отношения к текущему пути не имеет. cmd.exe обычно запускается с текущим каталогом %SystemRoot%\System32.
Чтоб перейти в каталог, где лежит батник, используйте команду: cd /d "%~dp0"
Пути можно получать из параметров батника, указанным способом, то же самое можно делать для переменных цикла, и параметров процедур. Список доступных модификаторов (буквы после %~ доступны в описании команд call и for.

Пригласить эксперта

команда ls, или же через проводник


  • Показать ещё
    Загружается…

Минуточку внимания

Maintained on

When using Command Prompt or batch files, it is often necessary to display the current directory (working directory).

By understanding the current directory, it becomes easier to manipulate files and folders, and work can be done more efficiently.

This article introduces the command to display the current directory and its applications.

Command to Display Current Directory

To display the current directory, use the cd command.

Executing from Command Prompt

×

Command Prompt

Microsoft Windows [Version xx.x.xxxxx.xxx]

(c) 2024 Ribbit App Development All rights reserved.

C:\users\user>cd

Executing from a Batch File

@echo off
setlocal

cd

endlocal
exit

Applying the Current Directory: Moving to the Temporary Directory

The cd command displays the current working directory when no arguments are specified, but it can also be used to move the current directory by specifying arguments.

Here’s how to use the current directory to move to a temporary directory.

Executing from Command Prompt

×

Command Prompt

Microsoft Windows [Version xx.x.xxxxx.xxx]

(c) 2024 Ribbit App Development All rights reserved.

C:\users\user>cd %TEMP%

Executing from a Batch File

@echo off
setlocal

cd %TEMP%

endlocal
exit

By using this method, you can easily move to a temporary directory and work on it.

Applying the Current Directory: Manipulating Files and Folders with Relative Paths

Using the current directory, you can manipulate files and folders with relative paths.

Here’s an example of how to move the sample.txt file in the current directory to the backup folder in the parent directory.

Executing from Command Prompt

×

Command Prompt

Microsoft Windows [Version xx.x.xxxxx.xxx]

(c) 2024 Ribbit App Development All rights reserved.

C:\users\user>move sample.txt ..\backup\

Executing from a Batch File

@echo off
setlocal

set FILE=sample.txt
set DEST=..\backup\

move %FILE% %DEST%

endlocal
exit

By using the current directory, you can manipulate files and folders with relative paths. This allows you to create more concise and flexible commands and batch files.

Summary

This article introduced the command to display the current directory and its applications.


#PowerShell

#Command Prompt

#Batch File

Posted: January 5, 2009/Under: Operating Systems/By:

When executing a batch command script (in .cmd or .bat file extension), sometimes it’s useful to get to know the current working directory of the batch script. Knowing the current directory or working folder in batch command is useful to ensure that the script is calling command or program at correct path, or manipulation of file and folder is done at valid destination when using relative path. Another important usage is to capture and save the current directory for later use, and the script may change the path during its course.

In fact, the showing and displaying of current directory is easy with the use of pseudo-variable for cmd.exe environment variables. From Windows 2000 onwards, Microsoft Windows has added %CD% pseudo-variable that expands to the current working directory.

For example, to display current working directory, just use the following command:

Echo %CD%

To save and store the current directory where a file is located for later use after change directory (cd) to other folder to perform other operations, use the following commands:

Set CURRENTDIR=%CD%

The %CURRENTDIR% variable to store the current working directory, which can be used in later batch commands, which as changing back to this previous directory.

In Windows 9x, the %CD% pseudo-variable is not existed. To get the current directory, use the following trick:

CD | Time | Find ":\" > Temp1.Bat
Echo Set CD=%%4 %%5 %%6 %%7 %%8 %%9 > Enter.Bat
Call Temp1.Bat
Del Temp1.Bat
Del Enter.Bat

The end result is a variable %CD% been returned to the batch processing session which contains the current working directory.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Добавление файла в исключения windows defender
  • Upnp как включить на компьютере windows 11
  • Pci ven 1106 dev 3106 subsys 14051186 rev 8b windows xp
  • Ricoh sp 212suw драйвер для windows 10
  • Как сделать чтобы панель задач была прозрачной windows 11