Windows cmd home directory

Есть ли в командной строке Windows команда быстрого доступа к домашнему каталогу текущего пользователя, как в Linux?

Я привык к использованию

чтобы попасть прямо в мой домашний каталог. В командной строке Windows я должен сделать

попасть туда. Есть ли ярлык как у Linux? Было бы неплохо, если бы я мог попасть туда, делая

Возможно ли что-то подобное в Windows Vista?

Вы всегда можете поместить .bat-файл где-нибудь в вашем% PATH%, который изменяет путь для вас.

Да, вы можете использовать %HOMEPATH% полный путь к домашнему каталогу пользователя.

Есть довольно много других полезных переменных, таких как %OS% (Операционная система) или %WINDIR% (системный каталог Windows). См. Wikipedia: Переменные среды для списка.

На самом деле, все немного сложнее (как обычно). %HOMEPATH% содержит только путь, без буквы диска, поэтому не будет работать cd с другого диска. Вы также можете использовать %USERPROFILE% , который делает содержать букву диска, и, как правило , в этом же каталоге %HOMEPATH% .

Значения этих переменных и то, какая из них вам подходит, будут зависеть от версии Windows и любых изменений, внесенных администратором, поскольку их значения могут отличаться (см., Например, вопрос « Разница между профилем и домашним путем» ).

Две другие опции, которые могут быть добавлены в скрипт и автоматически выполнены аналогично ответу BillP3rd.

Это еще два персонажа, но .

Конечно, вы не можете использовать это

в путях, но как быстрая «прыжок в мою домашнюю директорию» печатать

Enter довольно быстро.

Я создал файл .cmd в каталоге на моем пути и назвал его «cd

.cmd». Его содержимое:

Таким образом, я могу набрать «cd

» из любого места, чтобы попасть в мой домашний каталог. Не то же самое, что «cd

» (обратите внимание на отсутствующее место), но достаточно близко для меня.

Ответ sleske в почти совершенно верно, но это не всегда работает.

Если ваш домашний каталог находится в сетевой папке, настроенной как подключенный диск, запустите следующее независимо от диска текущего каталога:

/D Переключатель необходимо , чтобы cd изменить диски.

Есть ли ярлык для C:\Users\ \ ?

Там нет прямого ярлыка.

Есть несколько разных решений (см. Ниже).

Используйте переменную окружения вместе с cd или cd /d

Используйте subst или net use для создания сопоставления с другой буквой диска.

Установить cygwin и использовать bash

Использование powershell — поддержка powershell

Последнее решение, вероятно, самое простое, если вы готовы использовать powershell вместо cmd .

Решение 1. Используйте переменную среды вместе с cd или cd /d

Если вы хотите регулярно переходить в этот каталог, выполните следующую команду:

Это навсегда установит переменную окружения DOCS , но чтобы использовать ее, вам нужно сначала запустить новую cmd оболочку, а затем переменная определена и готова к использованию:

Чтобы изменить каталог из любого места, используйте следующую команду:

Если вы уже находитесь на диске, c: вы можете просто использовать:

Создайте командный файл ( docs.cmd ) и поместите его где-нибудь в свой PATH .

docs.cmd:

Затем вы можете просто ввести docs независимо от вашего текущего местоположения, и это приведет вас к C:\Users\

Читайте также:  How to get ram info linux

Решение 2. Используйте subst или net use для создания сопоставления с другой буквой диска.

Вы можете использовать subst :

К сожалению, сопоставления дисков не сохраняются при перезагрузке.

net use будет сохраняться при перезагрузке, например:

Решение 3. Установите cygwin и используйте bash

Вы можете рассмотреть возможность установки Cygwin :

  • большая коллекция инструментов GNU и Open Source, которые предоставляют функциональность, аналогичную дистрибутиву Linux в Windows.

После того, как вы установили Cygwin, вы можете запустить его bash в терминале Cygwin и установить соответствующую переменную окружения bash HOME .

Альтернативы cygwin включают в себя msys (MingW) :

MSYS — это набор утилит GNU, таких как bash, make, gawk и grep, позволяющих создавать приложения и программы, которые зависят от традиционных инструментов UNIX. Он предназначен для дополнения MinGW и недостатков оболочки cmd.

Git для Windows предоставляет эмуляцию BASH, используемую для запуска Git из командной строки. * Пользователи NIX должны чувствовать себя как дома, поскольку эмуляция BASH ведет себя так же, как команда «git» в средах LINUX и UNIX.

Решение 4: Используйте powershell

Как указано в комментарии к другому вопросу, который поддерживает SBI powershell,

What is the alternative for

I’m trying to use the command prompt to move some files, I am used to the linux terminal where I use

to specify the my home directory I’ve looked everywhere but I couldn’t seem to find it for windows command prompt ( Documents and Settings\[user] )

11 Answers 11

You’re going to be disappointed: %userprofile%

You can use other terminals, though. Powershell, which I believe you can get on XP and later (and comes preinstalled with Win7), allows you to use

for home directory.

You can %HOMEDRIVE%%HOMEPATH% for the drive + \docs settings\username or \users\username .

You can use %systemdrive%%homepath% environment variable to accomplish this.

The two command variables when concatenated gives you the desired user’s home directory path as below:

Running echo %systemdrive% on command prompt gives:

Running echo %homepath% on command prompt gives:

When used together it becomes:

Update — better version 18th July 2019.

Final summary, even though I’ve moved on to powershell for most windows console work anyway, but I decided to wrap this old cmd issue up, I had to get on a cmd console today, and the lack of this feature really struck me. This one finally works with spaces as well, where my previous answer would fail.

In addition, this one now is also able to use

as a prefix for other home sub-folders too, and it swaps forward-slashes to back-slashes as well. So here it is;

Step 1. Create these doskey macros, somewhere they get picked up every time cmd starts up.

Step 2. Create the cdtilde.bat file and put it somewhere in your PATH

Tested fine with;

Oh, also it allows lazy quoting, which I found useful, even when spaces are in the folder path names, since it wraps all of the arguments as if it was one long string. Which means just an initial quote also works, or completely without quotes also works.

All other stuff below may be ignored now, it is left for historical reasons — so I dont make the same mistakes again

old update 19th Oct 2018.
In case anyone else tried my approach, my original answer below didn’t handle spaces, eg, the following failed.

I think there must be a way to solve that. Will post again if I can improve my answer. (see above, I finally got it all working the way I wanted it to.)

My Original Answer, still needed work. 7th Oct 2018.
I was just trying to do it today, and I think I got it, this is what I think works well;

First, some doskey macros;

Is there a shortcut command in Windows command prompt to get to the current user’s home directory like there is in Linux?

I am used to using

Читайте также:  Как начать устанавливать windows с диска

to get right into my home directory. In Windows command prompt I have to do

to get there. Is there a shortcut like the Linux one? It would be nice if I could get there by doing

Is something like this possible in Windows Vista?

for the home directory. See also —-> stackoverflow.com/questions/9228950/… – franz1 Oct 4 ’19 at 9:53

12 Answers 12

You can always put a .bat file somewhere in your %PATH% which does the path changing for you.

Yes, you can use %HOMEPATH% , and %HOMEDRIVE% . These contain the full path of the user’s home directory (without drive letter), and the drive letter, respectively.

There are quite a few other useful variables available, such as %OS% (Operating System), or %WINDIR% (Windows system directory). See Wikipedia: Environment Variables for a list.

Actually, things are a bit complicated (as usual). There is also %USERPROFILE% , which does contain the drive letter, and is usually the same directory as %HOMEPATH% plus %HOMEDRIVE% .

The values of these variables, and which one is right for you, will depend on the Windows version and any changes by an administrator, as their values may be different (see e.g. the question Difference between profile and home path ).

Two other options both of which can be added to a script and auto-executed in a similar manner to BillP3rd’s answer.

It’s two more characters but.

Of course you can’t use this

in paths but as a quick «jump to my home dir» typing

Enter is pretty quick.

sleske’s answer is almost exactly right, but it doesn’t always work.

If your home directory is on a network share setup as a mapped drive, run the following regardless of the drive of the current directory:

The /D switch is necessary to allow cd to change drives.

I created a .cmd file in a directory in my PATH and named it cd

.cmd . Its contents are:

from anywhere to get to my home directory, though it’s not the same as cd

(note the missing space), but is close enough for me.

Is there a shortcut for C:\Users\ \ ?

There is no direct shortcut.

There are a couple of different solutions (see below).

Use an environment variable together with cd or cd /d

Use subst or net use to creating a mapping to another drive letter.

Install cygwin and use bash

Use powershell — powershell supports

The last solution is probably the simplest if you are prepared to use powershell instead of cmd .

Solution 1: Use an environment variable together with cd or cd /d

If you want to change to this directory on a regular basis then run the following command:

This will permanently set the environment variable DOCS , but in order to use use it you need to first start a new cmd shell, then the variable is defined and ready to use:

To change directory from any location use the following command:

If you are already on drive c: you can just use:

Create a batch file ( docs.cmd ) and put it somewhere in your PATH .

docs.cmd:

You can then just type docs regardless of your current location and it will take you to C:\Users\

Solution 2: Use subst or net use to creating a mapping to another drive letter.

You can use subst :

Unfortunately drive mappings do not persist across reboots.

net use will persist across reboots, for example:

Solution 3: Install cygwin and use bash

You could consider installing cygwin:

  • a large collection of GNU and Open Source tools which provide functionality similar to a Linux distribution on Windows.

Once you have installed cygwin you can run bash in a cygwin terminal and set the bash environment variable HOME as appropriate.

Читайте также:  Bulk image downloader linux

Alternatives to cygwin include msys (MingW):

MSYS is a collection of GNU utilities such as bash, make, gawk and grep to allow building of applications and programs which depend on traditionally UNIX tools to be present. It is intended to supplement MinGW and the deficiencies of the cmd shell.

Git for Windows provides a BASH emulation used to run Git from the command line. *NIX users should feel right at home, as the BASH emulation behaves just like the «git» command in LINUX and UNIX environments.

Solution 4: Use powershell

As pointed out in a comment on another question by SBI powershell supports

and you can just type:

Further Reading

  • An A-Z Index of the Windows CMD command line — An excellent reference for all things Windows cmd line related.
  • cd — Change Directory — Select a Folder (and drive)
  • setx — Set environment variables permanently, SETX can be used to set Environment Variables for the machine (HKLM) or currently logged on user (HKCU).
  • subst — Substitute a drive letter for a network or local path.

Dunno if its a feature of our work login script or a windows default, but I can use cd %HOMEPATH% to achieve that, where HOMEPATH is an environment variable.

I realize this is a long since done question, but just for the record. Install clink , this extends your command prompt in so many ways. Yes it it heavier then the above solutions but it makes the cmd window behave so much better.

resolves to the User\ directory. – THBBFT Feb 20 ’15 at 14:55

If you want all user’s commmand prompts to start in their «home» directory, create the following registry key as an Expandable String Value (sans quotes, of course):

If you want only your command prompts to do it:

I make it a practice to keep a C:\Scripts folder in which I keep an autoexec.bat file which I invoke via this key.

I used a better terminal (cmder) for this purpose. It has built in aliases and its very easy to use. Just read the documentation about Aliases here.

Windows has really become «all about the GUI», so in your case, I’d just get the tools you want instead of trying to «bend» the system to your will. The MinGW tools are an excellent little collection of some of the most widely used GNU tools and I highly recommend it if you’re a nix fan on Win.

I think everybody missed the main point: the purpose of cd

is to use the least number of keystrokes and not awkward percents, dollars, or tildes. and god forbid «cd %HOMEPATH%» or «cd %HOME%»

Since long time ago, I have with a c:\Tools\bats directory where I put my optimized minimum typing script named. cdd.bat..

So, why cdd.bat ? Why not home.bat or h.bat ? Simple: with home or h, you would have a little extra right hand shift movement to hit ‘h’,’o’,’m’ and still have to move the left hand once to hit ‘e’ while right hand waits to hit enter and also important, that makes 5 keystrokes for home, and only two for ‘h’ BUT right hand needs to shift around a bit. which I will trade off. With ‘h’, there is a little shift move of the entire right forearm to hit ‘h’ then ‘enter’. which I will also trade off

With ‘cdd’, though, both my hands already resting on the optimal keyboard place so there is no extra movement from either. Gets me 4 keystrokes while the first three are a quick succession.

You have to try and pay attention on a day to day bases to see the benefit.

Оцените статью