Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
114 views
in Technique[技术] by (71.8m points)

How to revert back from current working directory in batch file?

I need some help in writing a batch file.

In my file, file.bat, I have this:

SET path = "%CD%/../file.txt"

I am trying to go back one folder from the current working directory.

To be more understandable, my batch file is inside, C:/users/xy/xfolder/batfolder/file.bat, so I want to revert back to the C:/users/xy/xfolder.

I've tried using popd, or pushd, but neither works, (for me to revert back one folder.

How can I set path to go back one folder from the current working directory of the batch file?

question from:https://stackoverflow.com/questions/65921573/how-to-revert-back-from-current-working-directory-in-batch-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First: DO NOT use path as a variable name. %path% is a system variable that tells Windows where to find it's executables. Don't mess with it unless you know exactly what you do. Choose another name instead.

Second: your set syntax defines a variable %path %, and it's value starts with <space>"<space>C:.... And the correct path delimiter is a backslash, not a slash. Best, use this syntax: set "mypath=%cd%..file.txt"
%cd% is the "current working directory", which may or may not be identical with the "folder where the batch file is stored"

Third: the "folder, where your batch file is", is referenced as %~dp0, so your desired file should be "%~dp0..file.txt", where %~dp0 = "folder, where the batch file is stored", .. = "one folder up" and file.txt = "your desired file" (this is called a "relative path").
the "Folder where file.txt is stored, is just "%~dp0.."


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...