What is the alternative for ~ (user's home dir

2019-01-13 07:08发布

问题:

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])

回答1:

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.



回答2:

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



回答3:

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:

C:

Running echo %homepath% on command prompt gives:

\Users\<CurrentUserName>

When used together it becomes:

C:\Users\<CurrentUserName>


回答4:

You can do almost the same yourself. Open Environment Variables and click "New" Button in the "User Variables for ..." .
Variable Name: ~
Variable Value: Click "Browse Directory..." button and choose a directory which you want.

And after this, open cmd and type this:
cd %~%
. It works.



回答5:

I just tried set ~=%userprofile% and that works too if you want to keep using the same habit

You can then use %~% instead.



回答6:

Update 19th Oct 2018.
In case anyone else tries my approach, my original answer below doesnt handle spaces, eg, the following fails.

> cd "c:\Program Files"
Files""]==["~"] was unexpected at this time.

I think there must be a way to solve that. Will post again if I can improve my answer.


My Original Answer, still needs 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;

DOSKEY cd=cdtilde.bat $* 
DOSKEY cd~=chdir /D "%USERPROFILE%"
DOSKEY cd..=chdir ..

and then then a bat file in my path;

cdtilde.bat

@echo off
if ["%1"]==["~"] ( 
    chdir /D "%USERPROFILE%"
) else ( 
    chdir /D %* 
)

All these seem to work fine;

cd ~ (traditional habit)
cd~  (shorthand version)
cd.. (shorthand for going up..)


回答7:

If you want a shorter version of Jay's you could try

    set usr=%userprofile%
    cd %usr%

Or you could even use %u% if you wanted to. It saves some keystrokes anyway.



回答8:

Just wrote a script to do this without too much typing while maintaining portability as setting ~ to be %userprofile% needs a manual setup on each Windows PC while cloning and setting the directory as part of the PATH is mechanical.

https://github.com/yxliang01/Snippets/blob/master/windows/



回答9:

You can also do cd ......\ as many times as there are folders that takes you to home directory. For example, if you are in cd:\windows\syatem32, then cd ....\ takes you to the home, that is c:\