147

I used to work on bash and benefit a lot from alias. Is there any equivalent way in Windows Command Line?

I don't want to simulate a Linux environment, so cygwin is not a choice. I just need some shortcut for some very long command, like cd a_very_long_path.

StarPinkER
  • 1,593
  • 2
  • 10
  • 6

9 Answers9

126

As Christian.K said in his comment, the DOSKEY command can be used to define macros, which are analogous to aliases.

doskey macroName=macroDefinition

Macro parameters are referenced in the definition via $ prefixed positions: $1 through $9 and $* for all.

See the doskey technet documentation, or type doskey /? or help doskey from the command line for more information.

But there are serious limitations with DOSKEY macros:

  • The macros only work on the interactive command line - they do not work within a batch script.
  • They cannot be used on either side of a pipe: Both someMacro|findstr '^' and dir|someMacro fail.
  • They cannot be used within a FOR /F commands: for /f %A in ('someMacro') do ... fails

The limitations are so severe that I rarely use DOSKEY macros.

Obviously you can create batch scripts instead of macros, and make sure the script locations are in your PATH. But then you must prefix each script with CALL if you want to use the script within another script.

You could create simple variable "macros" for long and oft used commands, but syntax is a bit awkward to type, since you need to expand the "macro" when you want to use it.

Definition:

set "cdMe=cd a_very_long_path"

Usage (from command line or script)

%cdMe%
dbenham
  • 11,794
40

You can make a batch script and save it into your path.

Add %USERPROFILE%\bin to your PATH environment variable. Then save your scripts in there.

quickcd.cmd

@echo off
cd /d a_very_long_path

Now you can type quickcd at the command line.

It can also be called inside a script using the call function

call quickcd
O'Rooney
  • 327
23

subst

If you're really trying to get around something like this:

C:> cd \users\myLoginID\documents\clients\MTV\strategy\roadmap\deliverable\final

You can use the subst command to map that long path to a separate drive letter

subst m: c:\users\myLoginID\documents\clients\MTV\strategy\roadmap\deliverable\final

Then, when you want to jump into that folder, you can just type m: at the command line.

The advantage of this over doskey is that it works in all batch programs, and shows up in any file dialog box within Windows.

If you don't want the mapping any more:

subst m: /D
12

You could use the same trick, that windows uses: set an environment-variable (or just a variable in a batch-context) for example there is an environment-variable %windir% (and some others) So you can do an

cd C:\Windows\

or

cd %windir%

which does the same. So all, you have to do is:

set "mydir=C:\very\long\path\to\my\data\"

after that you can do (from whereever you are):

dir %mydir%

or

cd %mydir%

or whatever you want.

stephan
  • 121
11

You can use doskey.exe, here is an example:

doskey qcd=cd [pathname]

And now if you type qcd then it will cd to that path.

Here is some help with doskey macro's:

doskey [macroname]=[command]

That is the simplest form, here is an example:

doskey word=echo This is a really, really long sentence.

and if you type word the output is:

This is a really, really long sentence.

You can use $1-$9 for parameters, here is an example:

doskey npd=notepad $1

and if you type npd it will open notepad but if we type npd test.txt it will open test.txt in notepad.

You can use $* for all parameters, here is another example:

doskey prt=echo $*

and if you type prt This is short. then the output will be:

This is short.

You can use $T for multiple commands, here is an example:

doskey newline=echo $1 $T echo $2

and if you type newline Hello and then the output will be:

Hello

and

I hope you understand.

Hayz
  • 141
2

.cmdrc, the most convenient unix-like experience

  • Loads automatically with every instance of cmd
  • Doesn't require keyword DOSKEY for aliases
    example: ls=ls --color=auto $*

note: This answer is ported and refined version of SO: Aliases in Windows command prompt

cmd greetings & aliases

How to make it work?

  1. Create a new folder in your home, mkdir %userprofile%\cmd
    (If you choose a different name, don't forget to update everything below)

  2. Create a cmdrc.cmd and an aliases.mac files in the folder

  3. Register it in Registry to run on each instance of cmd
    note: It is also possible to only run it via a shortcut and not as Autorun

%userprofile%/cmd/cmdrc.cmd

:: This file is registered via registry to auto load with each instance of cmd.
:: HKEY_CURRENT_USER\Software\Microsoft\Command Processor
:: https://superuser.com/a/1858414/99602  -  how to set it up?

@echo off doskey /macrofile=%userprofile%\cmd\aliases.mac

:: put other commands here

cls echo Hi Qwerty, how are you today?

You can put other commands in this file: setting env variables, path, configuring prompt, changing directory, etc.

%userprofile%/cmd/aliases.mac

;==============================================================================
;= This file is registered via registry to auto load with each instance of cmd.
;= HKEY_CURRENT_USER\Software\Microsoft\Command Processor
;================================ general info ================================
;= https://superuser.com/a/1858414/99602  -  how to set it up?
;= https://gist.github.com/postcog/5c8c13f7f66330b493b8  -  example doskey macrofile
;===================== loading with cmd shortcut instead ======================
;= create a cmd link with the following target :
;= %comspec% /k "(doskey /macrofile=%userprofile%\cmd\aliases.mac)"

aliases=echo Opening aliases in Sublime... && subl %USERPROFILE%\cmd\aliases.mac ;= ga <name> -A <n> | -B <n> | -C <n> = show surrounding lines - After, Before, Combined ga=grep --color "$1" %USERPROFILE%\cmd\aliases.mac $2 $3 $4 $5

;= Commands ls=ls --color=auto $* ll=ls -l --color=auto $* la=ls -la --color=auto $* grep=grep --color $*

;= Directories ~=cd %USERPROFILE% cdr=cd C:\repos cdd=cd C:\Users\Qwerty\Downloads

;= GIT gpu =git push origin HEAD -u gpuf =git push origin HEAD -u --force gpuv =git push origin HEAD -u --no-verify gpufv=git push origin HEAD -u --force --no-verify gc =git checkout $* gcd=git checkout $1 --detach $2 $3 gco=git checkout origin/$1 --detach $2 $3 gwt =git worktree $* gwta=cd .git-worktrees && ( git worktree add $1 $1 && cp ../.env $1/.env & cd $1 & code . ) gwtr=git worktree remove $1 & git branch -D $1 & git worktree list

;= History support history=doskey /history h=IF ".$." == ".." (echo "usage: h [ SAVE | TAIL [-|+<n>] | OPEN ]" && echo. && doskey/history) ELSE (IF /I "$1" == "OPEN" (%USERPROFILE%\cmd\history.log) ELSE (IF /I "$1" == "SAVE" (echo *** %date% %time% **** >> %USERPROFILE%\cmd\history.log & doskey/history >> %USERPROFILE%\cmd\history.log & ECHO Command history saved) ELSE (IF /I "$1" == "TAIL" (tail $2 %USERPROFILE%\cmd\history.log) ELSE (doskey/history)))) exit=echo **** %date% %time% **** >> %USERPROFILE%\cmd\history.log & doskey/history >> %USERPROFILE%\cmd\history.log & exit $*

;============================= :end ============================ ;= rem ****************************************************************** ;= rem * EOF - Don't remove the following line. It clears out the ';' ;= rem * macro. We're using it because there is no support for comments ;= rem * in a DOSKEY macro file. ;= rem ****************************************************************** ;=

Notes about this macrofile's commands

aliases will open the aliases.mac in an editor of your choice for quick adjustments
ga lists all or searches for a command using grep in aliases.mac
ga alias -C 1 searches for "alias" and additionally prints one surrounding line
exit if you exit cmd with this command (and not the X button), it will save the session history to a history.log file
h outputs current session's history
h OPEN opens said history.log file in a text editor
h TAIL -2 reads last two entries from history.log file

%userprofile%/cmd/cmdrc.reg

Either manually addd the Autorun entry in registry, or run the .reg file.
note: The Autorun_ is just a placeholder key which will not do anything. Pick one and rename the other.

Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Microsoft\Command Processor]
"Autorun"="%USERPROFILE%\\cmd\\cmdrc.cmd"
"Autorun_"="doskey /macrofile=%userprofile%\\cmd\\aliases.mac"
Qwerty
  • 586
2

I've made an "alias" like that specifically for changing directory. Basically I created a file named fav.bat and put it into a folder in PATH (e.g C:\MyBatches):

@setlocal
@echo off
set userChoice=%1
rem The format is:
rem call :condition SHORTCUT FOLDER
call :condition web c:\Git\SecThor\SecWeb\App\
call :condition cloud c:\Git\SecThor\SecCloud\dojo.backend\
call :condition good c:\Users\Vitaly\Dropbox\Projects\goodread-friends\
endlocal
popd
GOTO :eof

:condition
rem We do PUSHD twice since endlocal does popd once :|
if "%userChoice%"=="%1" pushd %2 & pushd %2 & echo pushd %2
if "%userChoice%"=="" echo %1 =^> %2
GOTO :eof

Then I can jump to any predefined folder very quickly. I wrote a full article about that technique here.

VitalyB
  • 255
1

This is an old question, but was still #2 result when googling this issue before I found a fix so I'll share my solution.

  1. Create a folder for your scripts C:\shell-scripts
  2. Add created folder to PATH
  3. Inside that folder, create a alias.cmd and/or alias.ps1 (depending on if you use CMD or PowerShell)
  4. Contents of file:
    • pushd "C:\some\path\here"
      
  5. Make sure you close and re-open your terminal to load PATH
  6. Run alias

Note on my machine I was able to make both a .cmd and a .ps1 file with the same name without conflicts so I can use the alias in either PowerShell or CMD.

0

assuming you remain on the same drive, i.e. no D: then cd D:\somedir\ needed.

In my case, C: holds system files, but all work is on D:

2 parts. first set some working directories, using a batch file.

let's say localprofile.cmd. You can have multiple ones of these, just run them as needed.

set wd1=D:\home\work\fb440.dumper
set wd2=D:\home\work\py\tests

now use another command file to move around, based on those environment variables you just set.

wd.cmd

echo off
d:
if %1.==. set | findstr wd
if %1==1 cd %wd1%
if %1==2 cd %wd2%
if %1==3 cd %wd3%
if %1==4 cd %wd4%
if %1==5 cd %wd5%
if %1==6 cd %wd6%

And a bit of a sample use:

D:\home\bin>wd 2

D:\home\bin>echo off
D:\home\work\py\tests>wd 1

D:\home\work\py\tests>echo off

wd by itself is supposed to show me the list of bookmarked directories. It works, but not sure why I am getting this "unexpected cd" message.

D:\home\work\fb440.dumper>wd

D:\home\work\fb440.dumper>echo off
wd1=D:\home\work\fb440.dumper
wd2=D:\home\work\py\tests
cd was unexpected at this time.

D:\home\work\fb440.dumper> 

Regular .cmd batches

Aside from directory navigation, you can create a foo.cmd somewhere on your PATH and it can act much as an alias. Remember, unlike Linux/OSX shells, cmd files can affect environment variables and the session, without needing to source them.

I have a cdbin.cmd to navigate me, for example:

d:
cd \home\bin

And this is a pseudo-grep grep.cmd

findstr -n %1 %2

in action (whatever sort /+2 /+10 means)

D:\home\work\fb440.dumper>grep class *.py | sort /+2 /+10

dumper2.py:18:class PrettySafeLoader(yaml.SafeLoader):            
dumper2.py:27:class Comparator(object):                           
dumper2.py:3:class module_settings:                               
linker2.py:5:class module_settings:                               
dumper2.py:65:class DataCompProcessor(object):                    
dumper2.py:69:class DataCompTextRenderer(DataCompProcessor):      
dumper2.py:76:class DataComparator(object):                       
JL Peyret
  • 884