【cmd】变量总结

来源:互联网 发布:农村淘宝服务站地址 编辑:程序博客网 时间:2024/06/16 01:04

cmd变量通过set设置变量,通过可以使用set /?查看有关变量的帮助文档。

接下来谈set的用法:

1.set 变量名=值

值可以包含空格、一直到命令结束,也可以是Ctrl+G这种代表警报声的字符(echo输出会发出警报声“滴~”),与echo类似


2.set 变量名

在系统中预定义了一批环境变量(所有的环境变量将附加在博客尾),如最常见的path变量,记录了系统应用程序的默认路径,如果仅仅使用set 变量名,那么将会打印所有以这个变量名开头的变量为的值。例如如果set p,将会打印ProgramFiles, ProgramFIles(X86), path等以p开头的变量的值。如果用户通过set设置了新的变量,如set pt=point那么新变量在这个cmd中将加入环境变量,因此set p也将会打印出pt的值,与环境变量不同的是,该变量只在当前cmd有效,同时对环境变量的更改也只是在当前cmd有效。


3.set /P 变量=提示

变量将通过用户输入接收值,提示作为提示信息输出,例如set /p v=输入v的值:,那么将会出现

输入v的值

(等待输入)


4.set /A 变量=表达式

表达式将被视为算术表达式,变量赋值为算术表达式的值,算术运算符参照帮助文档或者官方网站文档(可以发现,与C语言运算符基本相同)

   +   Add                set /a "_num=_num+5"   +=  Add variable       set /a "_num+=5"   -   Subtract (or unary)set /a "_num=_num-5"   -=  Subtract variable  set /a "_num-=5"   *   Multiply           set /a "_num=_num*5"   *=  Multiply variable  set /a "_num*=5"   /   Divide             set /a "_num=_num/5"   /=  Divide variable    set /a "_num/=5"   %   Modulus            set /a "_num=5%%2"   %%= Modulus            set /a "_num%%=5"    !   Logical negation  0 (FALSE) ⇨ 1 (TRUE) and any non-zero value (TRUE) ⇨ 0 (FALSE)   ~   One's complement (bitwise negation)    &   AND                set /a "_num=5&3"    0101 AND 0011 = 0001 (decimal 1)   &=  AND variable       set /a "_num&=3"   |   OR                 set /a "_num=5|3"    0101 OR 0011 = 0111 (decimal 7)   |=  OR variable        set /a "_num|=3"   ^   XOR                set /a "_num=5^3"    0101 XOR 0011 = 0110 (decimal 6)   ^=  XOR variable       set /a "_num=^3"   <<  Left Shift.    (sign bit ⇨ 0)   >>  Right Shift.   (Fills in the sign bit such that a negative number always remains negative.)                       Neither ShiftRight nor ShiftLeft will detect overflow.   <<= Left Shift variable     set /a "_num<<=2"   >>= Right Shift variable    set /a "_num>>=2"  ( )  Parenthesis group expressions  set /a "_num=(2+3)*5"   ,   Commas separate expressions    set /a "_num=2,_result=_num*5"

如果要使用其他变量的值,需要使用%变量名%(或者 !变量名!)来表示该变量。同时0X与0分别表示十六进制与八进制数字。


5.%变量名:str1=str2%

表示将变量的值中包含的str1使用str2替换后获得的变量,例如

set a="minecraft great!"

echo %a: = is so %

echo %a 

此时将会输出:

minecraft is so great!

minecraft great!

这里将空格替换为( is so ),因此输出minecraft is so great!,而%a%依然如故,说明原变量并没有发生变化


6.%变量名(已定义):~start[, length]%

表示从start出开始(包括start,第一个计数为0),取length长的子串,如果length省略,则表示取到串尾,start可以为负数,最后一个字符为-1,从后往前依次为-2、-3、-4……


7.setlocal [Enable|Disable]DelayedExpansion

执行cmd或者bat文件是从头向后执行,变量有一个扩展规则,即在执行一个语句块时变量将会被变量的值代替,例如

set a=hello& echo a

这个语句通过&连接成为一个语句块,又如

(set a=steve

if defined a echo hello %a%)

是通过()组合的一个语句块

在执行语句块时,a将会被a的值所代替,而语句块中的set语句将会在该语句块执行完后才有效,例如

set a=hello

(set a=steve

if defined a echo hello %a%)

将会输出hello而不是steve,可以理解为当前语句块中所有的set都在下一句语句块执行时才有效,在当前语句块不做任何事情

这样将会对程序的逻辑性产生很大的影响,为了解决这个问题,我们可以使用setlocal EnableDelayExpansion。

EnableDelayedExpansion,直接翻译为“启用扩展延迟”,这个我们可以理解为原来的情况是在执行语句块时所有的变量都被扩展为值了,此时还未执行set命令,而启用后,扩展被延迟到语句块执行结束时,此时set命令已经执行,原来变量的值已经被set为了新的值,因此set已经生效。注意,启用后变量的调用将会变为!变量名!,如果使用%变量名%,调用的将会是未使用扩展延迟的状态的变量(即与原来没什么区别),与之相对的还有setlocal DisableDelayedExpansion,为相反的效果。

当执行这个命令后,在执行endlocal之前,setlocal将会一直生效,因此EndLocal就是将setlocal的效果“终结”的命令,使用后,setlocal(无论enable还是disable),效果都将end,一个setlocal对应一个endlocal


8.setlocal [Enable|Disable]Extensions

启用或者禁用Extension,部分cmd命令拥有启用Extension后的“额外”功能,如果没有启用,那么功能不可用,如if。


9.setlocal

setlocal将表示setlocal后直到endlocal,所有的变量都是局部变量,例如

@echo off
set b=1
setlocal
set b=2
setlocal 
set b=3
set c=hi
echo %b% %c%
endlocal
echo %b% 
if defined c echo %c%
endlocal
if defined c echo %b% %c%

输出为

3 hi

2


10.for %i in (set) do

在文件(bat或者cmd)中需要将%i使用%%i来代替,%%i不会出现变量扩展的问题,在循环中同步更新%%i的值(谢天谢地,一切正常)


11.bat/cmd文件 + 参数1 + 参数2 + 参数3 + ……

通过%1,%2,%3表示对参数1、2、3……的引用,%0表示bat文件的绝对路径+文件名,如C:\Users\Administrator\Desktop\test.bat

12.最后附上系统预定义环境变量表(里面居然还有产生随机数的变量+_+,比较有用的变量已红):

Standard (built-in) Environment Variables

VariableVolatile
(Read-Only)Default value in Windows 7/10/2008 (assuming the system drive is C: )ALLUSERSPROFILE C:\ProgramDataAPPDATA C:\Users\{username}\AppData\RoamingCDYThe current directory (string).ClientNameYTerminal servers only - the ComputerName of a remote host.CMDEXTVERSIONYThe current Command Processor Extensions version number. (NT = "1", Win2000+ = "2".)CMDCMDLINEYThe original command line that invoked the Command Processor.CommonProgramFiles C:\Program Files\Common FilesCOMMONPROGRAMFILES(x86) C:\Program Files (x86)\Common FilesCOMPUTERNAME {computername}COMSPEC C:\Windows\System32\cmd.exe or if running a 32 bit WOW - C:\Windows\SysWOW64\cmd.exeDATEYThe current date using same region specific format as DATE.ERRORLEVELYThe current ERRORLEVEL value, automatically set when a program exits.FPS_BROWSER_APP_PROFILE_STRING
FPS_BROWSER_USER_PROFILE_STRING
 Internet Explorer
Default
These are undocumented variables for the Edge browser in Windows 10.HighestNumaNodeNumberY (hidden)The highest NUMA node number on this computer.HOMEDRIVEYC:HOMEPATHYC:\Users\{username}LOCALAPPDATA C:\Users\{username}\AppData\LocalLOGONSERVER \\{domain_logon_server}NUMBER_OF_PROCESSORSYThe Number of processors running on the machine.OSYOperating system on the user's workstation.PATHUser and
SystemC:\Windows\System32\;C:\Windows\;C:\Windows\System32\Wbem;{plus program paths}PATHEXT .COM; .EXE; .BAT; .CMD; .VBS; .VBE; .JS ; .WSF; .WSH; .MSC
The syntax is like the PATH variable - semicolon separators.PROCESSOR_ARCHITECTUREYAMD64/IA64/x86 This doesn't tell you the architecture of the processor but only of the current process, so it returns "x86" for a 32 bit WOW process running on 64 bit Windows. See detecting OS 32/64 bitPROCESSOR_ARCHITEW6432 =%ProgramFiles% (only available on 64 bit systems)PROCESSOR_IDENTIFIERYProcessor ID of the user's workstation.PROCESSOR_LEVELYProcessor level of the user's workstation.PROCESSOR_REVISIONYProcessor version of the user's workstation.ProgramW6432 =%PROCESSOR_ARCHITECTURE% (only available on 64 bit systems)ProgramData C:\ProgramDataProgramFiles C:\Program FilesProgramFiles(x86) 1 C:\Program Files (x86)PROMPT Code for current command prompt format,usually $P$G
C:>PSModulePath %SystemRoot%\system32\WindowsPowerShell\v1.0\Modules\Public C:\Users\PublicRANDOMYA random integer number, anything from 0 to 32,767 (inclusive).%SessionName% Terminal servers only - for a terminal server session, SessionName is a combination of the connection name, followed by #SessionNumber. For a console session, SessionName returns "Console".SYSTEMDRIVE C:SYSTEMROOT By default, Windows is installed to C:\Windows but there's no guarantee of that, Windows can be installed to a different folder, or a different drive letter.
systemroot is a read-only system variable that will resolve to the correct location.
NT 4.0, Windows 2000 and Windows NT 3.1 default to C:\WINNTTEMP and TMPUser VariableC:\Users\{Username}\AppData\Local\Temp
Under XP this was \{username}\Local Settings\TempTIMEYThe current time using same format as TIME.UserDnsDomainY
User VariableSet if a user is a logged on to a domain and returns the fully qualified DNS domain that the currently logged on user's account belongs to.USERDOMAIN {userdomain}USERDOMAIN_roamingprofile The user domain for RDS or standard roaming profile paths. Windows 8/10/2012 (or Windows 7/2008 with Q2664408)USERNAME {username}USERPROFILE %SystemDrive%\Users\{username}
This is equivalent to the $HOME environment variable in Unix/LinuxWINDIR 

%WinDir% pre-dates Windows NT and seems to be superseded by %SystemRoot%
Set by default as windir=%SystemRoot%
%windir% is a regular variable and can be changed, which makes it less robust than %systemroot%


13.总结

  学习一门语言,首先是从学习它的数据类型开始的,cmd或者说batch作为一个脚本语言,自然也是需要学习一下变量部分,总结一下,batch中的变量为弱类型,支持“切片操作”,可以设置局部变量,变量存在“扩展”的问题,提供了用户输入的接口以及支持一部分基本的数值运算,可以实现一部分简单的操作,虽然比不上C等编程语言的数据结构的强大性,但是可以满足一般的需求,如果涉及到复杂的运算或者数据结构,就需要考虑使用其他语言(如python等)来完成。系统的环境变量虽然“红”了那么多,但是实际上最有用的可能还是path和cd这两个变量了。

0 0
原创粉丝点击