How can I return to the previous directory in windows command prompt? - command-line

I often want to return to the previous directory I was just in in cmd.exe, but windows does not have the "cd -" functionality of Unix. Also typing cd ../../.. is a lot of typing.
Is there a faster way to go up several directory levels?
And ideally return back afterwards?

This worked for me in powershell
cd ..

Steps:
pushd . (Keep old folder path on the stack)
cd ..\.. (Move to the folder whare you like to)
popd (Pop it from the stack. Meaning, Come back to the old folder)

On Windows CMD, I got used to using pushd and popd. Before changing directory I use pushd . to put the current directory on the stack, and then I use cd to move elsewhere. You can run pushd as often as you like, each time the specified directory goes on the stack. You can then CD to whatever directory, or directories , that you want. It does not matter how many times you run CD. When ready to return , I use popd to return to whatever directory is on top of the stack. This is suitable for simple use cases and is handy, as long as you remember to push a directory on the stack before using CD.

Run cmd.exe using the /k switch and a starting batch file that invokes doskey to use an enhanced versions of the cd command.
Here is a simple batch file to change directories to the first parameter (%1) passed in, and to remember the initial directory by calling pushd %1.
md_autoruns.cmd:
#echo off
cd %1
pushd %1
title aliases active
cls
%SystemRoot%\System32\doskey.exe /macrofile=c:\tools\aliases
We will also need a small helper batch file to remember the directory changes and to ignore changes to the same directory:
mycd.bat:
#echo off
if '%*'=='' cd & exit /b
if '%*'=='-' (
cd /d %OLDPWD%
set OLDPWD="%cd%"
) else (
cd /d %*
if not errorlevel 1 set OLDPWD="%cd%"
)
And a small aliases file showing what to do to make it all work:
aliases:
cd=C:\tools\mycd.bat $*
cd\=c:\tools\mycd.bat ..
A:=c:\tools\mycd.bat A:
B:=c:\tools\mycd.bat B:
C:=c:\tools\mycd.bat C:
...
Z:=c:\tools\mycd.bat Z:
.=cd
..=c:\tools\mycd.bat ..
...=c:\tools\mycd.bat ..\..
....=c:\tools\mycd.bat ..\..\..
.....=c:\tools\mycd.bat ..\..\..\..
......=c:\tools\mycd.bat ..\..\..\..\..
.......=c:\tools\mycd.bat ..\..\..\..\..\..
........=c:\tools\mycd.bat ..\..\..\..\..\..\..
.........=c:\tools\mycd.bat ..\..\..\..\..\..\..\..
tools=c:\tools\mycd.bat C:\tools
wk=c:\tools\mycd.bat %WORKSPACE%
Now you can go up a directory level by typing ..
Add another . for each level you want to go up.
When you want to go back, type cd - and you will be back where you started.
Aliases to jump to directories like wk or tools (shown above) swiftly take you from location to location, are easy to create, and can really help if you work in the command line frequently.

You could use the command:
cd ..\ -> To go up one level
cd ..\..\ -> To go up two levels
Note the space after cd

Related

Calling Date Modified in CMD

Basically just attempting to create a very basic program that will display the last modified date of a file on our server. Problem is I have no idea how to write it. This is what I attempted
cd \\Server\Folder
msg dir
I also ran into the problem "CMD Does not support UNC Paths as Current Directories" when I tried to change the CD to our servers directory.
What I would like it to do is display in a dialog box the modified date of a "Text.txt" located on our server \\Server\Folder
Any and all help is appreciated
Next .bat script should work:
set "_folder=\\Server\Folder"
set "_filename=Text.txt"
set "_filedatetime=N/A"
pushd %_folder%
for %%G in (%_filename%) do (
rem echo %%~tG %%~fG
if not "%%~tG"=="" set "_filedatetime=%%~tG"
)
popd
echo file %_folder%\%_filename% date and time: %_filedatetime%
Note there is no dialog box in pure cmd command line interpreter, try set /P.
Resources:
SET: Display, set, or remove CMD environment variables
PUSHD, POPD: and UNC Network paths
FOR commands
~ Parameter Extensions

cd - 1>&2 >/dev/null doesn't work right on Solaris

I use a command in a script for AIX and RHEL:
cd - 1>&2 >/dev/null
I know that this is trying to go back to the previous directory after changing to another directory.
While the exact same logic works for AIX and RHEL, it’s apparently not quite working on Solaris, with the error that I got implying that there’s no previous directory to go back to, when in fact the script had change the directory to /etc/opt/esmsym.
How to make this work on Solaris?
Do you have an alternative?
try running:
cd $OLDPWD
That should take you back to the previous working directory.
Or, if that doesn't work then you could try using this:
export path=$(pwd)
cd ~/B/
cd $path
This saves a copy of the current path to the $path variable and then changes the current directory to ~/B/ and then uses the $path variable to return the to previous working directory.
Just as a side-note, there's also podp and pushd
pushd $(pwd)
cd /tmp
popd
Taken from popd(1):
pushd pushes a directory onto the directory stack. With no arguments, exchange the top two elements.
+n
Rotate the n’th entry to the top of the stack and cd to it.
dir
Push the current working directory onto the stack and change to dir.
popd pops the directory stack and cd to the new top directory. The elements of
the directory stack are numbered from 0 starting at the top.
+n
Discard the n’th entry in the stack.

Importing Projects and Building workspace from batch file

I have this batch file
#ECHO OFF
ECHO Please Enter Path of the View, you want to update in double quotes.
SET /P variable=
SET ECLIPSE=C:\Users\gdeep\Desktop\TED-4.3.0.20110512190809.lnk
SET WORKSPACE=C:\Users\gdeep\DevCodebase_2
:LOOP
ECHO Press 'g' for Graphical Interface and 'c' for Command line.
SET /P answer=
IF /I "%answer%"=="g" GOTO GRAPHICAL
IF /I "%answer%"=="c" GOTO COMMANDLINE
ECHO Invalid Input. Please Try Again.
GOTO LOOP
:GRAPHICAL
cleartool update -graphical %variable%
GOTO CONTINUE
:COMMANDLINE
cleartool update %variable%
GOTO CONTINUE
:CONTINUE
FOR /D %%i IN (%WORSPACE%) DO RD /S /Q "%%i" DEL /Q "%WORSPACE%\*.*"
START %ECLIPSE% -data %WORSPACE%
D:
chdir "%variable%"\v4electronics
ECHO Please Ensure that Server is killed.
PAUSE
mvn clean install -Dmaven.test.skip=true -Dresource.minify.skip=true
For deleting all the projects i used
FOR /D %%i IN (%WORSPACE%) DO RD /S /Q "%%i" DEL /Q "%WORSPACE%\*.*"
Can anyone explain this to me? I copied it from somewhere and don't want to use it without understanding.
Problem with using above command is althout it seem to work, i see
The system cannot find the file specified.
The system cannot find the path specified.
as the output.
Also, the way i am deleting, will it be equivalent to if i delete them from the eclipse, by select all projects and deleting?
Another problem here is that when i have .
mvn clean install -Dmaven.test.skip=true -Dresource.minify.skip=true
in the end it works fine, otherwise, if there is any other command after it, those commands doesn't run.
After this, I then wanna import all maven projects from the Clearcase %Variable%.
And i want to do that by command line only. Can you help me with that?
Thanks for your help.
Appreciate your time.
Please correct me, If I'm wrong. I understand that you're in the MS-Windows environment.
Regarding to the question about if there is another command after the "mvn ...", they are ignored.
I use the "call" as the following: -
cd project1
call mvn clean install
cd project2
call mvn clean install
I hope this may help.
Regards,
Charlee Ch.
cleartool update -graphical %variable%
This will update a view, opening a GUI during the update (if -graphical is used) for displaying the number of files unchanged, new, modified, deleted or hijacked during this update.
See cleartool update man page.
The graphical update will let you specify how you want hijacked files and timestamps handled by said update:
Click the Advanced tab and change default options for the Update Tool.
If you need to resolve hijacked files, select a method. You have these choices:
Leave hijacked files in place
Rename the hijacked files and load the selected version from the VOB
Delete hijacked files and load the selected version from the VOB
You can also select a method for handling timestamps. You have these choices:
Set file times to current time
Set file times to version creation time
You need to enter the path of the root directory of a snapshot view: see "To update snapshot views"
FOR /D %%i IN (%WORSPACE%) DO RD /S /Q "%%i" DEL /Q "%WORSPACE%\*.*"
This will completely empty Eclipse workspace, projects and its .metadata folder, forcing Eclipse to recreate a workspace from scratch.
It seems a bit extreme, and would basically be the same as
RD /S /Q "%WORSPACE%"
(Eclipse would recreate "%WORSPACE%" when launched with -data %WORSPACE%)

Command line to recursively delete files but excluding a certain file

I need to delete files of a certain type (.zip files, say) from a folder, and all of its sub-folders, using the command line. Ideally I am looking for something that can be run as a .bat file in Windows.
I know there is a /S switch for the DEL command to look in sub-folders, but to add to the challenge I need to exclude files of a certain name ("Backup.zip" as an example).
Is there a way to delete files recursively but exclude files of a certain name. It will not be practical in my situation to explicitly list all the file names I want to delete, only the files of the matching type I don't want to delete.
A nice trick: make the files you want to exclude read-only!
DEL /S will not delete read-only file.
The following script does not do exactly what you want (see my remarks below) but shows you how read-only files can be used to avoid deletion.
#ECHO OFF
:: This example supposes your first parameter is
:: the relative path to the folder to be deleted
:: and the second is the relative path (from the
:: the target folder) of the one to be excluded
:: Notice that this will only work if the folders
:: are in the working drive, if not, you ll
:: have to specify full paths
IF "%1"=="" GOTO ERROR
IF "%2"=="" GOTO ERROR
IF NOT EXIST %1\NUL GOTO ERROR
CD %1
IF NOT EXIST %2\NUL GOTO ERROR
ECHO Starting up the deletion process
ECHO. * Setting attributes
attrib %1\*.mp3 -r -s -h > NUL
attrib %2\*.mp3 +r > NUL
ECHO. * Deleting files
del /s %1\*.mp3
ECHO. * Reseting attributes
attrib %2\*.mp3 -r > NUL
ECHO.
ECHO Operation completed!
ECHO.
GOTO END
:ERROR
ECHO Parameters:
ECHO. Param1 -> target folder
ECHO. Param2 -> folder to be ignored
ECHO.
GOTO END
:END
Note: you can adapt this script in order to ignore not just a sub-folder but all files of given type:
attrib /S *.xxx +r > NUL
will in effect help you to exclude all 'xxx' files of the current directory and all sub-directories (hence the /S option).
Note: the "> NUL" part is a redirection often used to hide standard output, instead of displaying it on screen.
It can be dangerous if used too often (in a large loop with different paths involved, for instance) since it is a device, and like all devices (AUX, COMn, LPTn, NUL and PRN):
opening a device will claim one file handle. However, unlike files, devices will never be closed until reboot.
each device exists in every directory on every drive, so if you used redirection to NUL in, say, C:\ and after that you use it again in C:\TEMP, you'll lose another file handle.
Just do this, easy
windows button + r
type cmd and hit enter
Navigate to parent directory:
type c: or d: (or letter of the drive you want to navigate to)
type dir to see a list of that directory's contents ( dir /ah to see hidden files )
then to change directory, type cd xxxx ( xxxx = directory name )
Repeat 4&5 until you get to the directory where you want to run the batch delete
then type your pattern. Something like: del /S /ah *.jpg and hit enter. It will run through all sub-directories, and remove all visible and hidden files that are .jpg files
* is a wildcard
/S deletes from all subfolders
/ah a = select files based on attribute, h = hidden
Example: to delete those annoying .DS_Store files that appear when you copy from Mac to Windows, run:
del /S /ah .DS_Store
or
del /S /ah ._*
which will get all the 'duplicate' hidden files that are also created when copying from Mac to Windows.
You can easily loop a set of files and perform a command on each one, like this:
set match=D:\blah\M*.zip
for %%x in (%match%) do (
del %%x
)
Then I think you need to read this article on how to manipulate strings in DOS:
http://www.dostips.com/DtTipsStringManipulation.php
You can simply use below:
forfiles /p C:\temp-new /s /c "cmd /c if #isdir==FALSE del #file"
TechNet Referenceenter link description here
Perhaps the 'forfiles' command could be of use
http://technet.microsoft.com/en-us/library/cc753551.aspx
Hope that helps.
This script will delete all .zip files from a folder (and subfolders), BUT ONLY IF the file name does not contain the word "backup", or "Backup" or "BACKUP", etc.
# Script DeleteZip.txt
var str folder, filelist, file
cd $folder
lf -r -n "*.zip" > $filelist
while ($filelist <> "")
do
lex "1" $filelist > $file
# Does this $file contain the word "backup" ? Do case independent search (-c option).
if ( { sen -c "^backup^" $file } <= 0 )
system del ("\""+$file+"\"")
endif
done
Script is in biterscripting ( http://www.biterscripting.com ). Save the script in file C:/Scripts/DeleteZip.txt. Run the script as
script "C:/Scripts/DeleteZip.txt" folder("C:/testfolder")
Will do the delete operation on folder C:/testfolder and all its subfolders, at all levels.
A simple way that you need:
FORFILES /P "DIRECTORY" /S /M SEARCHMASK /C "cmd /c if #file neq \"FILE_TO_EXCLUDE\" del /f #file"
You still can adapt the command to your need to exclude specific files and/or by date. More details in the 'forfiles' documentation below.
https://learn.microsoft.com/pt-br/windows-server/administration/windows-commands/forfiles

Tool for commandline "bookmarks" on windows?

Im searching a tool which allows me to specify some folders as "bookmarks" and than access them on the commandline (on Windows XP) via a keyword. Something like:
C:\> go home
D:\profiles\user\home\> go svn-project1
D:\projects\project1\svn\branch\src\>
I'm currently using a bunch of batch files, but editing them by hand is a daunting task. On Linux there is cdargs or shell bookmarks but I haven't found something on windows.
Thanks for the Powershell suggestion, but I'm not allowed to install it on my box at work, so it should be a "classic" cmd.exe solution.
What you are looking for is called DOSKEY
You can use the doskey command to create macros in the command interpreter. For example:
doskey mcd=mkdir "$*"$Tpushd "$*"
creates a new command "mcd" that creates a new directory and then changes to that directory (I prefer "pushd" to "cd" in this case because it lets me use "popd" later to go back to where I was before)
The $* will be replaced with the remainder of the command line after the macro, and the $T is used to delimit the two different commands that I want to evaluate. If I typed:
mcd foo/bar
at the command line, it would be equivalent to:
mkdir "foo/bar"&pushd "foo/bar"
The next step is to create a file that contains a set of macros which you can then import by using the /macrofile switch. I have a file (c:\tools\doskey.macros) which defines the commands that I regularly use. Each macro should be specified on a line with the same syntax as above.
But you don't want to have to manually import your macros every time you launch a new command interpreter, to make it happen automatically, just open up the registry key
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun and set the value to be doskey /macrofile "c:\tools\doskey.macro". Doing this will make sure that your macros are automatically predefined every time you start a new interpreter.
Extra thoughts:
- If you want to do other things in AutoRun (like set environment parameters), you can delimit the commands with the ampersand. Mine looks like: set root=c:\SomeDir&doskey /macrofile "c:\tools\doskey.macros"
- If you prefer that your AutoRun settings be set per-user, you can use the HKCU node instead of HKLM.
- You can also use doskey to control things like the size of the command history.
- I like to end all of my navigation macros with \$* so that I can chain things together
- Be careful to add quotes as appropriate in your macros if you want to be able to handle paths with spaces in them.
I was looking for this exact functionality, for simple cases. Couldn't find a solution, so I made one myself:
#ECHO OFF
REM Source found on https://github.com/DieterDePaepe/windows-scripts
REM Please share any improvements made!
REM Folder where all links will end up
set WARP_REPO=%USERPROFILE%\.warp
IF [%1]==[/?] GOTO :help
IF [%1]==[--help] GOTO :help
IF [%1]==[/create] GOTO :create
IF [%1]==[/remove] GOTO :remove
IF [%1]==[/list] GOTO :list
set /p WARP_DIR=<%WARP_REPO%\%1
cd %WARP_DIR%
GOTO :end
:create
IF [%2]==[] (
ECHO Missing name for bookmark
GOTO :EOF
)
if not exist %WARP_REPO%\NUL mkdir %WARP_REPO%
ECHO %cd% > %WARP_REPO%\%2
ECHO Created bookmark "%2"
GOTO :end
:list
dir %WARP_REPO% /B
GOTO :end
:remove
IF [%2]==[] (
ECHO Missing name for bookmark
GOTO :EOF
)
if not exist %WARP_REPO%\%2 (
ECHO Bookmark does not exist: %2
GOTO :EOF
)
del %WARP_REPO%\%2
GOTO :end
:help
ECHO Create or navigate to folder bookmarks.
ECHO.
ECHO warp /? Display this help
ECHO warp [bookmark] Navigate to existing bookmark
ECHO warp /remove [bookmark] Remove an existing bookmark
ECHO warp /create [bookmark] Navigate to existing bookmark
ECHO warp /list List existing bookmarks
ECHO.
:end
You can list, create and delete bookmarks. The bookmarks are stored in text files in a folder in your user directory.
Usage (copied from current version):
A folder bookmarker for use in the terminal.
c:\Temp>warp /create temp # Create a new bookmark
Created bookmark "temp"
c:\Temp>cd c:\Users\Public # Go somewhere else
c:\Users\Public>warp temp # Go to the stored bookmark
c:\Temp>
Every warp uses a pushd command, so you can trace back your steps using popd.
c:\Users\Public>warp temp
c:\Temp>popd
c:\Users\Public>
Open a folder of a bookmark in explorer using warp /window <bookmark>.
List all available options using warp /?.
With just a Batch file, try this... (save as filename "go.bat")
#echo off
set BookMarkFolder=c:\data\cline\bookmarks\
if exist %BookMarkFolder%%1.lnk start %BookMarkFolder%%1.lnk
if exist %BookMarkFolder%%1.bat start %BookMarkFolder%%1.bat
if exist %BookMarkFolder%%1.vbs start %BookMarkFolder%%1.vbs
if exist %BookMarkFolder%%1.URL start %BookMarkFolder%%1.URL
Any shortcuts, batch files, VBS Scripts or Internet shortcuts you put in your bookmark folder (in this case "c:\data\cline\bookmarks\" can then be opened / accessed by typing "go bookmarkname"
e.g. I have a bookmark called "stack.url". Typing go stack takes me straight to this page.
You may also want to investigate Launchy
With PowerShell you could add the folders as variables in your profile.ps1 file, like:
$vids="C:\Users\mabster\Videos"
Then, like Unix, you can just refer to the variables in your commands:
cd $vids
Having a list of variable assignments in the one ps1 file is probably easier than maintaining separate batch files.
Another alternative approach you may want to consider could be to have a folder that contains symlinks to each of your projects or frequently-used directories. So you can do something like
cd \go\svn-project-1
cd \go\my-douments
Symlinks can be made on a NTFS disk using the Junction tool
Without Powershell you can do it like this:
C:\>set DOOMED=c:\windows
C:\>cd %DOOMED%
C:\WINDOWS>
Crono wrote:
Are Environment variables defined via "set" not meant for the current session only? Can I persist them?
They are set for the current process, and by default inherited by any process that it creates. They are not persisted to the registry. Their scope can be limited in cmd scripts with "setlocal" (and "endlocal").
Environment variables?
set home=D:\profiles\user\home
set svn-project1=D:\projects\project1\svn\branch\src
cd %home%
On Unix I use this along with popd/pushd/cd - all the time.