Menu
- Batch File Local Variables Vs Global Variables Definition
- Dos Batch File Variable Assignment
- Static Variables
- Batch File Variables Input
Mar 01, 2013 Variable Scope (Global vs Local) By default, variables are global to your entire command prompt session. Call the SETLOCAL command to make variables local to the scope of your script. After calling SETLOCAL, any variable assignments revert upon calling ENDLOCAL, calling EXIT, or when execution reaches the end of file (EOF) in your script.
Environment variables are mainly used within batch files, they can be created, modified and deleted for a session using the SET command. To make permanent changes, use SETX
Variables can be displayed using either SET or ECHO.
Variables can be displayed using either SET or ECHO.
Variables have a percent sign on both sides: %ThisIsAVariable%
The variable name can include spaces, punctuation and mixed case: %_Another Ex.ample%
(This is unlike Parameter variables which only have one % sign and are always one character long: %A )
The variable name can include spaces, punctuation and mixed case: %_Another Ex.ample%
(This is unlike Parameter variables which only have one % sign and are always one character long: %A )
A variable name may include any of the following characters:
A-Z, a-z, 0-9, # $ ' ( ) * + , - . ? @ [ ] _ ` { } ~
The first character of the name must not be numeric.
A-Z, a-z, 0-9, # $ ' ( ) * + , - . ? @ [ ] _ ` { } ~
The first character of the name must not be numeric.
Array variables
Unlike PowerShell, which fully supports arrays, there is no built in support for array variables within the CMD shell. However with some effort you can replicate this functionality using a series of separate variables, named to represent the array:
Set elem[1]=First element
Set elem[2]=Second one
Set elem[3]=The third one
Set elem[2]=Second one
Set elem[3]=The third one
To perform array indexing operations with these, use EnableDelayedExpansion and a reference like !elem[%var%]!
this is explained fully in this StackOverflow Q/A.
this is explained fully in this StackOverflow Q/A.
Standard (built-in) Environment Variables
Variable | Volatile (Read-Only) | Default value in Windows 7/10/2008 (assuming the system drive is C: ) |
---|---|---|
ALLUSERSPROFILE | C:ProgramData | |
APPDATA | C:Users{username}AppDataRoaming | |
CD | Y | The current directory (string). |
ClientName | Y | Terminal servers only - the ComputerName of a remote host. |
CMDEXTVERSION | Y | The current Command Processor Extensions version number. (NT = '1', Win2000+ = '2'.) |
CMDCMDLINE | Y | The original command line that invoked the Command Processor. |
CommonProgramFiles | C:Program FilesCommon Files | |
COMMONPROGRAMFILES(x86) | C:Program Files (x86)Common Files | |
COMPUTERNAME | {computername} | |
COMSPEC | C:WindowsSystem32cmd.exe or if running a 32 bit WOW - C:WindowsSysWOW64cmd.exe | |
DATE | Y | The current date using same region specific format as DATE. |
ERRORLEVEL | Y | The 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. | |
HighestNumaNodeNumber | Y (hidden) | The highest NUMA node number on this computer. |
HOMEDRIVE | Y | C: |
HOMEPATH | Y | Users{username} |
LOCALAPPDATA | C:Users{username}AppDataLocal | |
LOGONSERVER | {domain_logon_server} | |
NUMBER_OF_PROCESSORS | Y | The Number of processors running on the machine. |
OS | Y | Operating system on the user's workstation. |
PATH | User and System | C:WindowsSystem32;C:Windows;C:WindowsSystem32Wbem;{plus program paths} |
PATHEXT | .COM; .EXE; .BAT; .CMD; .VBS; .VBE; .JS ; .WSF; .WSH; .MSC Determine the default executable file extensions to search for and use, and in which order, left to right. The syntax is like the PATH variable - semicolon separators. | |
PROCESSOR_ARCHITECTURE | Y | AMD64/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 bit |
PROCESSOR_ARCHITEW6432 | =%PROCESSOR_ARCHITECTURE% (but only available to 64 bit processes) | |
PROCESSOR_IDENTIFIER | Y | Processor ID of the user's workstation. |
PROCESSOR_LEVEL | Y | Processor level of the user's workstation. |
PROCESSOR_REVISION | Y | Processor version of the user's workstation. |
ProgramW6432 | =%ProgramFiles%(but only available when running under a 64 bit OS) | |
ProgramData | C:ProgramData | |
ProgramFiles | C:Program Files or C:Program Files (x86) | |
ProgramFiles(x86)1 | C:Program Files (x86) (but only available when running under a 64 bit OS) | |
PROMPT | Code for current command prompt format,usually $P$G C:> | |
PSModulePath | %SystemRoot%system32WindowsPowerShellv1.0Modules | |
Public | C:UsersPublic | |
RANDOM | Y | A 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:WINNT | |
TEMP and TMP | User Variable | C:Users{Username}AppDataLocalTemp Under XP this was {username}Local SettingsTemp |
TIME | Y | The current time using same format as TIME. |
UserDnsDomain | Y User Variable | Set 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/Linux | |
WINDIR | %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% |
1 Only on 64 bit systems, is used to store 32 bit programs.
Unless stated otherwise, all the variables above are System variables
Environment variables are stored in the registry:
User Variables: HKEY_CURRENT_USEREnvironment
System Variables: HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment
System Variables: HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment
By default, files stored under Local Settings do not roam with a roaming profile.
Dynamic environment variables are read-only and are computed each time the variable is expanded. When all variables are listed with SET, these will not appear in the list. Do not attempt to directly SET a dynamic variable.
Undocumented Dynamic variables (read only)
%__APPDIR__% The directory path to the current application .exe, terminated with a trailing backslash. (Global) - discuss
%__CD__% The current directory, terminated with a trailing backslash. (Global)
%=C:% The current directory of the C: drive. ( See Raymond Chen's explanation of this.)
%=D:% The current directory of the D: drive if drive D: has been accessed in the current CMD session.
%DPATH% Related to the (deprecated) DPATH command.
%=ExitCode% The most recent exit code returned by an external command, such as CMD /C EXIT n, converted to hex.
%=ExitCodeAscii% The most recent exit code returned by an external command, as ASCII. (Values 0-32 do not display because those map to ASCII control codes.)
%FIRMWARE_TYPE% The boot type of the system: Legacy ,UEFI,Not implemented ,Unknown Windows 8/2012.
%KEYS% Related to the (deprecated) KEYS command.
More detail on these undocumented variables can be found in this stackoverflow answer from Dave Benham.
%__CD__% The current directory, terminated with a trailing backslash. (Global)
%=C:% The current directory of the C: drive. ( See Raymond Chen's explanation of this.)
%=D:% The current directory of the D: drive if drive D: has been accessed in the current CMD session.
%DPATH% Related to the (deprecated) DPATH command.
%=ExitCode% The most recent exit code returned by an external command, such as CMD /C EXIT n, converted to hex.
%=ExitCodeAscii% The most recent exit code returned by an external command, as ASCII. (Values 0-32 do not display because those map to ASCII control codes.)
%FIRMWARE_TYPE% The boot type of the system: Legacy ,UEFI,Not implemented ,Unknown Windows 8/2012.
%KEYS% Related to the (deprecated) KEYS command.
More detail on these undocumented variables can be found in this stackoverflow answer from Dave Benham.
Undocumented Dynamic variables (read/write)
%__COMPAT_LAYER% Set the ExecutionLevel to either RunAsInvoker (asInvoker), RunAsHighest(highestAvailable) or RunAsAdmin(requireAdministrator) for more see elevation and Q286705 / Application Compatibility Toolkit for other Compatibility Layers (colours,themes etc).
Pass variables between batch scripts
There are several ways to pass values between batch files, or between a batch file and the command line, see the CALL and SETLOCAL pages for full details.
A child process by default inherits a copy of all environment variables from its parent, this makes environment variables unsuitable for storing secret information such as API keys or user passwords, especially in rare occasions like crashes where a crash log will often include the full OS environment at the time of the crash. PowerShell/Get-Credential is a more secure approach.
If Command Extensions are disabled, the following dynamic variables will be not accessible:
%CD% %DATE% %TIME% %RANDOM% %ERRORLEVEL% %CMDEXTVERSION% %CMDCMDLINE% %HIGHESTNUMANODENUMBER%
%CD% %DATE% %TIME% %RANDOM% %ERRORLEVEL% %CMDEXTVERSION% %CMDCMDLINE% %HIGHESTNUMANODENUMBER%
“Men may be convinced, but they cannot be pleased against their will. But though taste is obstinate, it is very variable, and time often prevails when arguments have failed” ~ Samuel Johnson
Related:
Related:
PowerShell - Working with Environment variables
User Shell Folders - Profile, Start Menu - Location of user profile folders.
Detecting 32 vs 64 bit Windows
CALL - Evaluate environment variables.
SET - View environment variables, set local variables.
SETX - Set environment variables.
Q100843 - The four types of environment variable.
Q286705 - Set compatibility variables in a batch file.
Q242557 - Registry Settings for Folder Redirection.
StackOverflow - Storing a Newline in a variable.
User Shell Folders - Profile, Start Menu - Location of user profile folders.
Detecting 32 vs 64 bit Windows
CALL - Evaluate environment variables.
SET - View environment variables, set local variables.
SETX - Set environment variables.
Q100843 - The four types of environment variable.
Q286705 - Set compatibility variables in a batch file.
Q242557 - Registry Settings for Folder Redirection.
StackOverflow - Storing a Newline in a variable.
Copyright © SS64.com 1999-2019
Some rights reserved
Some rights reserved
< A-level Computing | AQA | Paper 1 | Fundamentals of programming
PAPER 1 - ⇑ Fundamentals of programming ⇑ | ||
← Subroutines (functions and procedures) | Global and local variables | Stack Frames → |
Global variable - declared at the start of the program, their global scope means they can be used in any procedure or subroutine in the program
Batch File Local Variables Vs Global Variables Definition
It is seldom advisable to use Global variables as they are liable to cause bugs, waste memory and can be hard to follow when tracing code. If you declare a global variable it will continue to use memory whilst a program is running even if you no longer need/use it.
Local variable - declared within subroutines or programming blocks, their local scope means they can only be used within the subroutine or program block they were declared in
Local variables are initiated within a limited scope, this means they are declared when a function or subroutine is called, and once the function ends, the memory taken up by the variable is released. This contrasts with global variables which do not release memory.
Take a look at this example:
Dos Batch File Variable Assignment
What would the output be?
Code Output
123
234
123
234
123
Why is this? Well we seem to have two versions of the variable number1.
- The first version is declared on line 2, this isn't declared inside any sub routines so the variable has Global scope
- The second version is declared inside the printLocalNumber sub routine. As it is declared inside a sub routine it is only able to be used inside this subroutine. And on line 12 when we use:
console.writeline(number1)
it prints out the local variable
So looking at the code inside the main sub routine we have 3 different ways of printing out the variable number1.
Static Variables
- Line 5.
console.writeline(number1)
:This uses the global value of number1, as it is inside a sub routine with no other local declarations - Line 6.
printLocalNumber()
:This is calling on the subroutineprintLocalNumber()
which has a local variable number1 contained within it on line 11, therefore it uses the number1 value declared on line 11. - Line 7.
printGlobalNumber()
:This is calling on the subroutineprintGlobalNumber()
which has no local variable for number1, therefore it uses the global value for number1
Batch File Variables Input
We can visualise the scope of the different variables
Rules of thumb: If you want to quickly tell the difference between a global and a local variable use these quick rules. But be warned they might try to trick you!
- If a variable is declared inside a function or a procedure it is a local variable
- If a variable is declared inside an iterative or selective statement it is local
- If the declaration is indented from the left hand boundary it probably meets one of the above criteria and is local
- If it meets none of the above statements and is declared in the main body of code it is a global variable
Title What is the difference between a global and a local variable? Answer: Global variables are accessible from all parts of a program, whilst local variables are only accessible within a programming construct such as a loop, function or procedure Why is it a good idea to use local variables instead of global variable? Answer: Local variables release memory when you have finished with them, global variables are always stored in memory whether you need them or not In what situation might you want to use a global variable? Answer: When you want to declare a variable that needs to be accessible by all parts of your code List the global and local variables for the following. What will be the output for input 16 :Answer: Locals: age, d Globals: months Now try the. Windows 7 Activator Free Download The only way that you can enjoy the full features of the windows is to get yourself a valid activator, the activator of the windows 7 is very easy to install, deactivate your anti-virus, run and install the activator. Windows 7 activation all version: software free download free. Reboot the computer and now you can enjoy the full features of the windows 7. It works in all languages of the system, it supports 64 bit system as well as 32 bit system, the tool is fully encrypted this means that security and the privacy of the computer remains protected. Code Output age? 16 192 5840 For the above code how could you make the code more efficient, and why would it be more efficient? Answer: Make the months variable a local variable by putting it inside the printMonths(a) sub routine, if you leave it as a global variable it will be taking up memory even when you don't need it.List the Global and Local variables in the following code, list the output: Answer: Locals: y (on line 4), q (on line 9) Globals: q (on line 2) Code Output 6 hi,bye,bye,bye,bye,bye,bye 6 |
Retrieved from 'https://en.wikibooks.org/w/index.php?title=A-level_Computing/AQA/Paper_1/Fundamentals_of_programming/Global_and_local_variables&oldid=3483534'