'Why won't a Batch file start in the directory it was executed in?
I am programming a DOS-like shell, but it starts in %UserProfile% instead of %UserProfile%\Desktop\Coding projects\CM-DOS. The actual shell, kernel.bat's code is:
@echo off
type INFO.txt
pause
INFO.txt is in the same directory as kernel.bat (CM-DOS). It says:
CM-DOS is a FREE, open-source Disk Operating System by Tristan Carpenter. If anyone trys to sell you a paid copy of CM-DOS, send me an e-mail at [email protected]. Please use this DOS shell kindly. This shell is licensed under the MIT License. Do whatever you want with the shell, create closed-source versions, fork it, I don't really care.
The script tries to type "%UserProfile%\INFO.txt", which doesn't exist. How can I start the file in it's actual directory, instead of %UserProfile%.
Solution 1:[1]
If you run the script (clicking or navigating (cd <folder>) and .\kernel.bat) and the current folder isn't, well, the current folder, then something is off with either your console setup or there is an additional code executed in the background. Try to echo %CD% to see what the folder is and check the prompt string usually in the shape of:
C:\Users\Username>
which is the default path if you run cmd.exe as a user or:
C:\Windows\System32>
if you run as an Administrator / user with elevated privileges.
This can be changed though with regedit.exe.
However what you might be seeing is that you run your code (kernel.bat or however you name it) which might display the first path before execution or after the last command you might be dropped into a shell. Neither should be the case according to the code, yet it can happen if you started cmd.exe, then wrote cmd.exe (i.e. spawned another shell) and then ran your script.
What I suspect is that you're running the code like this:
C:\Users\You> .\Desktop\Coding projects\CM-DOS\kernel.bat
in which case the %CD% would be C:\Users\You and type command would be looking for C:\Users\You\INFO.txt. A better solution is simply creating a variable for the folder where your script is located - which is provided automatically, it's %~dp0 (echo %~dp0) and with that you can do:
echo off
type "%~dp0INFO.txt"
pause
to make it location independent, or better said, to access relatively according to the kernel.bat (the current script)'s location.
Solution 2:[2]
You can add cd %CD%
and %CD% stands for the current direction.
the final code would be
@echo off
cd %CD%
type INFO.txt
pause
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | manhat |
