2024年6月30日 星期日

Batch Script - Decision Making

 If Statement

The first decision-making statement is the ‘if’ statement. The general form of this statement in Batch Script is as follows −

if(condition) do_something

The general working of this statement is that first a condition is evaluated in the ‘if’ statement. If the condition is true, it then executes the statements. The following diagram shows the flow of the if statement.

If Statement

Checking Variables

One of the common uses for the ‘if’ statement in Batch Script is for checking variables which are set in Batch Script itself. The evaluation of the ‘if’ statement can be done for both strings and numbers.

Checking Integer Variables

The following example shows how the ‘if’ statement can be used for numbers.

Example

@echo off 
SET /A a = 5 
SET /A b = 10 
SET /A c = %a% + %b% 
if %c%==15 echo "The value of variable c is 15" 
if %c%==10 echo "The value of variable c is 10"

The key thing to note about the above program is −

  • The first ‘if’ statement checks if the value of the variable c is 15. If so, then it echo’s a string to the command prompt.

  • Since the condition in the statement - if %c% == 10 echo "The value of variable c is 10 evaluates to false, the echo part of the statement will not be executed.

Output

The above command produces the following output.

15

Checking String Variables

The following example shows how the ‘if’ statement can be used for strings.

Example

@echo off 
SET str1 = String1 
SET str2 = String2 
if %str1%==String1 echo "The value of variable String1" 
if %str2%==String3 echo "The value of variable c is String3"

The key thing to note about the above program is −

  • The first ‘if’ statement checks if the value of the variable str1 contains the string “String1”. If so, then it echo’s a string to the command prompt.

  • Since the condition of the second ‘if’ statement evaluates to false, the echo part of the statement will not be executed.

Output

The above command produces the following output.

"The value of variable String1"

Note − One key thing to note is that the evaluation in the ‘if’ statement is "case-sensitive”. The same program as above is modified a little as shown in the following example. In the first statement, we have changed the comparison criteria. Because of the different casing, the output of the following program would yield nothing.

@echo off 
SET str1 = String1 
SET str2 = String2 
if %str1%==StrinG1 echo "The value of variable String1" 
if %str2%==String3 echo "The value of variable c is String3"

Checking Command Line Arguments

Another common use of the ‘if’ statement is used to check for the values of the command line arguments which are passed to the batch files. The following example shows how the ‘if’ statement can be used to check for the values of the command line arguments.

Example

@echo off 
echo %1 
echo %2 
echo %3 
if %1%==1 echo "The value is 1" 
if %2%==2 echo "The value is 2" 
if %3%==3 echo "The value is 3"

The key thing to note about the above program is −

  • The above program assumes that 3 command line arguments will be passed when the batch script is executed.

  • A comparison is done for each command line argument against a value. If the criteria passes then a string is sent as the output.

Output

If the above code is saved in a file called test.bat and the program is executed as

test.bat 1 2 3

Following will be the output of the above program.

1 
2 
3 
"The value is 1" 
"The value is 2" 
"The value is 3"
 
 
 
 
If/else Statement 

The next decision making statement is the If/else statement. Following is the general form of this statement.

If (condition) (do_something) ELSE (do_something_else)

The general working of this statement is that first a condition is evaluated in the ‘if’ statement. If the condition is true, it then executes the statements thereafter and stops before the else condition and exits out of the loop. If the condition is false, it then executes the statements in the else statement block and then exits the loop. The following diagram shows the flow of the ‘if’ statement.

If/else Statement

Checking Variables

Just like the ‘if’ statement in Batch Script, the if-else can also be used for checking variables which are set in Batch Script itself. The evaluation of the ‘if’ statement can be done for both strings and numbers.

Checking Integer Variables

The following example shows how the ‘if’ statement can be used for numbers.

Example

@echo off SET /A a = 5 SET /A b = 10 SET /A c = %a% + %b% if %c%==15 (echo "The value of variable c is 15") else (echo "Unknown value") if %c%==10 (echo "The value of variable c is 10") else (echo "Unknown value")

The key thing to note about the above program is −

  • Each ‘if else’ code is placed in the brackets (). If the brackets are not placed to separate the code for the ‘if and else’ code, then the statements would not be valid proper if else statements.

  • In the first ‘if else’ statement, the if condition would evaluate to true.

  • In the second ‘if else’ statement, the else condition will be executed since the criteria would be evaluated to false.

Output

The above command produces the following output.

"The value of variable c is 15" "Unknown value"

Checking String Variables

The same example can be repeated for strings. The following example shows how the ‘if else’ statement can be used to strings.

Example

@echo off SET str1 = String1 SET str2 = String2 if %str1%==String1 (echo "The value of variable String1") else (echo "Unknown value") if %str2%==String3 (echo "The value of variable c is String3") else (echo "Unknown value")

The key thing to note about the above program is −

  • The first ‘if’ statement checks if the value of the variable str1 contains the string “String1”. If so, then it echo’s a string to the command prompt.

  • Since the condition of the second ‘if’ statement evaluates to false, the echo part of the statement will not be executed.

Output

The above command produces the following output.

"The value of variable String1" "Unknown value"

Checking Command Line Arguments

The ‘if else’ statement can also be used for checking of command line arguments. The following example show how the ‘if’ statement can be used to check for the values of the command line arguments.

Example

@echo off echo %1 echo %2 echo %3 if %1%==1 (echo "The value is 1") else (echo "Unknown value") if %2%==2 (echo "The value is 2") else (echo "Unknown value") if %3%==3 (echo "The value is 3") else (echo "Unknown value")

Output

If the above code is saved in a file called test.bat and the program is executed as

test.bat 1 2 4

Following will be the output of the above program.

1 2 4 "The value is 1" "The value is 2" "Unknown value"

if defined

A special case for the ‘if’ statement is the "if defined", which is used to test for the existence of a variable. Following is the general syntax of the statement.

if defined somevariable somecommand

Following is an example of how the ‘if defined’ statement can be used.

Example

@echo off SET str1 = String1 SET str2 = String2 if defined str1 echo "Variable str1 is defined" if defined str3 (echo "Variable str3 is defined") else (echo "Variable str3 is not defined")

Output

The above command produces the following output.

"Variable str1 is defined" "Variable str3 is not defined"

if exists

Another special case for the ‘if’ statement is the "if exists ", which is used to test for the existence of a file. Following is the general syntax of the statement.

If exist somefile.ext do_something

Following is an example of how the ‘if exists’ statement can be used.

Example

@echo off if exist C:\set2.txt echo "File exists" if exist C:\set3.txt (echo "File exists") else (echo "File does not exist")

Output

Let’s assume that there is a file called set2.txt in the C drive and that there is no file called set3.txt. Then, following will be the output of the above code.

"File exists" "File does not exist"
 
 
 
 
 
 
Nested If Statements 

Sometimes, there is a requirement to have multiple ‘if’ statement embedded inside each other. Following is the general form of this statement.

if(condition1) if (condition2) do_something

So only if condition1 and condition2 are met, will the code in the do_something block be executed.

Following is an example of how the nested if statements can be used.

Example

@echo off SET /A a = 5 SET /A b = 10 if %a%==5 if %b%==10 echo "The value of the variables are correct"

Output

The above command produces the following output.

"The value of the variables are correct"

If errorlevel

Yet another special case is "if errorlevel", which is used to test the exit codes of the last command that was run. Various commands issue integer exit codes to denote the status of the command. Generally, commands pass 0 if the command was completed successfully and 1 if the command failed.

Following is the general syntax of this statement.

if errorlevel n somecommand

where "n" is one of the integer exit codes.

Goto Statement

Generally, the execution of a batch file proceeds line-by-line with the command(s) on each line being run in turn. However, it is often desirable to execute a particular section of a batch file while skipping over other parts. The capability to hop to a particular section is provided by the appropriately named "goto" command (written as one word). The target section is labeled with a line at the beginning that has a name with a leading colon. Thus the script looks like −

... goto :label ...some commands :label ...some other commands

Execution will skip over "some commands" and start with "some other commands". The label can be a line anywhere in the script, including before the "goto" command. "Goto" commands often occur in "if" statements. For example, you might have a command of the type −

if (condition) goto :label

Following is an example of how the goto statement can be used.

Example

@echo off SET /A a = 5 if %a%==5 goto :labela if %a%==10 goto :labelb :labela echo "The value of a is 5" exit /b 0 :labelb echo "The value of a is 10"

The key thing to note about the above program is −

  • The code statements for the label should be on the next line after the declaration of the label.

  • You can define multiple goto statements and their corresponding labels in a batch file.

  • The label declarations can be anywhere in the file.

Output

The above command produces the following output.

"The value of a is 5"
 

Batch Script - Arrays

 

Arrays are not specifically defined as a type in Batch Script but can be implemented. The following things need to be noted when arrays are implemented in Batch Script.

  • Each element of the array needs to be defined with the set command.
  • The ‘for’ loop would be required to iterate through the values of the array.

Creating an Array

An array is created by using the following set command.

set a[0]=1

Where 0 is the index of the array and 1 is the value assigned to the first element of the array.

Another way to implement arrays is to define a list of values and iterate through the list of values. The following example show how this can be implemented.

Example

@echo off 
set list=1 2 3 4 
(for %%a in (%list%) do ( 
   echo %%a 
))

Output

The above command produces the following output.

1
2
3
4

Accessing Arrays

You can retrieve a value from the array by using subscript syntax, passing the index of the value you want to retrieve within square brackets immediately after the name of the array.

Example

@echo off 
set a[0]=1 
echo %a[0]%

In this example, the index starts from 0 which means the first element can be accessed using index as 0, the second element can be accessed using index as 1 and so on. Let's check the following example to create, initialize and access arrays −

@echo off
set a[0]=1 
set a[1]=2 
set a[2]=3 
echo The first element of the array is %a[0]% 
echo The second element of the array is %a[1]% 
echo The third element of the array is %a[2]%

The above command produces the following output.

The first element of the array is 1 
The second element of the array is 2 
The third element of the array is 3

Modifying an Array

To add an element to the end of the array, you can use the set element along with the last index of the array element.

Example

@echo off 
set a[0]=1  
set a[1]=2  
set a[2]=3 
Rem Adding an element at the end of an array 
Set a[3]=4 
echo The last element of the array is %a[3]%

The above command produces the following output.

The last element of the array is 4

You can modify an existing element of an Array by assigning a new value at a given index as shown in the following example −

@echo off 
set a[0]=1 
set a[1]=2  
set a[2]=3 
Rem Setting the new value for the second element of the array 
Set a[1]=5 
echo The new value of the second element of the array is %a[1]%

The above command produces the following output.

The new value of the second element of the array is 5

Iterating Over an Array

Iterating over an array is achieved by using the ‘for’ loop and going through each element of the array. The following example shows a simple way that an array can be implemented.

@echo off 
setlocal enabledelayedexpansion 
set topic[0]=comments 
set topic[1]=variables 
set topic[2]=Arrays 
set topic[3]=Decision making 
set topic[4]=Time and date 
set topic[5]=Operators 

for /l %%n in (0,1,5) do ( 
   echo !topic[%%n]! 
)

Following things need to be noted about the above program −

  • Each element of the array needs to be specifically defined using the set command.

  • The ‘for’ loop with the /L parameter for moving through ranges is used to iterate through the array.

Output

The above command produces the following output.

Comments 
variables 
Arrays 
Decision making 
Time and date 
Operators

Length of an Array

The length of an array is done by iterating over the list of values in the array since there is no direct function to determine the number of elements in an array.

@echo off 
set Arr[0]=1 
set Arr[1]=2 
set Arr[2]=3 
set Arr[3]=4 
set "x = 0" 
:SymLoop 

if defined Arr[%x%] ( 
   call echo %%Arr[%x%]%% 
   set /a "x+=1"
   GOTO :SymLoop 
)
echo "The length of the array is" %x%

Output

Output The above command produces the following output.

1
2
3
4
"The length of the array is" 4

Creating Structures in Arrays

Structures can also be implemented in batch files using a little bit of an extra coding for implementation. The following example shows how this can be achieved.

Example

@echo off 
set obj[0].Name=Joe 
set obj[0].ID=1 
set obj[1].Name=Mark 
set obj[1].ID=2 
set obj[2].Name=Mohan 
set obj[2].ID=3 
FOR /L %%i IN (0 1 2) DO  (
   call echo Name = %%obj[%%i].Name%%
   call echo Value = %%obj[%%i].ID%%
)

The following key things need to be noted about the above code.

  • Each variable defined using the set command has 2 values associated with each index of the array.

  • The variable i is set to 0 so that we can loop through the structure will the length of the array which is 3.

  • We always check for the condition on whether the value of i is equal to the value of len and if not, we loop through the code.

  • We are able to access each element of the structure using the obj[%i%] notation.

Output

The above command produces the following output.

Name=Joe 
Value=1 
Name=Mark 
Value=2 
Name=Mohan 
Value=3

Batch Script - Strings

 

Example

@echo off 
:: This program just displays Hello World 
set message = Hello World 
echo %message%

Output

The above command produces the following output.

Hello World 

 

 

 

 

 

An empty string can be created in DOS Scripting by assigning it no value during it’s initialization as shown in the following example.

Set a=

To check for an existence of an empty string, you need to encompass the variable name in square brackets and also compare it against a value in square brackets as shown in the following example.

[%a%]==[]

The following example shows how an empty string can be created and how to check for the existence of an empty string.

Example

@echo off 
SET a= 
SET b=Hello 
if [%a%]==[] echo "String A is empty" 
if [%b%]==[] echo "String B is empty "
 

Output

The above command produces the following output.

String A is empty 

 

 

 

 

 

String interpolation is a way to construct a new String value from a mix of constants, variables, literals, and expressions by including their values inside a string literal.

In DOS scripting, the string interpolation can be done using the set command and lining up the numeric defined variables or any other literals in one line when using the set command.

The following example shows how a string interpolation can be done with numeric values as well.

Example

@echo off 
SET a = Hello 
SET b = World 
SET /A d = 50 
SET c=%a% and %b% %d%
echo %c%
 

Output

The above command produces the following output.

Hello and World 50 

 

 

 

 

 

You can use the set operator to concatenate two strings or a string and a character, or two characters. Following is a simple example which shows how to use string concatenation.

Example

@echo off 
SET a = Hello 
SET b = World 
SET c=%a% and %b% 
echo %c%

Output

The above command produces the following output.

Hello and World 
 
 
 
 
 

In DOS scripting, there is no length function defined for finding the length of a string. There are custom-defined functions which can be used for the same. Following is an example of a custom-defined function for seeing the length of a string.

Example

@echo off set str = Hello World call :strLen str strlen echo String is %strlen% characters long exit /b :strLen setlocal enabledelayedexpansion :strLen_Loop if not "!%1:~%len%!"=="" set /A len+=1 & goto :strLen_Loop (endlocal & set %2=%len%) goto :eof

A few key things to keep in mind about the above program are −

  • The actual code which finds the length of string is defined in the :strLen block.

  • The length of the string is maintained in the variable len.


    Output

    The above command produces the following output.

    11 
     
     
     
     
     
     

    Example

    @echo off set var = 13145 set /A var=%var% + 5 echo %var%

    Output

    The above command produces the following output.

    13150

    Apart from this, strings have the following implementations which are available. Batch scripts have the following commands which are used to carry out string manipulation in strings.

    %variable:~num_chars_to_skip% %variable:~num_chars_to_skip,num_chars_to_keep%

    This can include negative numbers −

    %variable:~num_chars_to_skip, -num_chars_to_keep% %variable:~-num_chars_to_skip,num_chars_to_keep% %variable:~-num_chars_to_skip,-num_chars_to_keep%

    Let us discuss the possible string operations that can be performed by using the above commands.

     

     

     

     

     

    Example

    @echo off 
    set x = 1000 
    set y = 1 
    set y = %y% 
    echo %x% 
    
    set y = %y:~-4% 
    echo %y%

    A few key things to note about the above program is −

  • Spaces are added to the variable of y, in this case we are adding 9 spaces to the variable of y.

  • We are using the ~-4 option to say that we just want to show the last 4 characters of the string y.

     

    Output

    The above command produces the following output. The key thing to note is that the value of 2 is aligned to match the units columns when displaying numbers.

    1000
    1 
     
     
     
     
     

    Example

    set str=Helloworld echo.%str% set str=%str:~0,5% echo.%str%

    The key thing to note about the above program is, ~0,5 is used to specify the characters which needs to be displayed. In this case, we are saying character 0 to 5 should be displayed.

    Output

    The above command produces the following output.

    Helloworld Hello 
  •  
     
     
     
     
     
     

    Example

    @echo off set str = Helloworld echo %str% set str = %str:~5,10% echo %str%

    The key thing to note about the above program is, ~5,10 is used to specify the characters which needs to be displayed. In this case, we want character 5 to 10 should be displayed.

     

    Output

    The above command produces the following output.

    Helloworld 
    world 
     
     
     
     
     

    Example

    @echo off set str = Batch scripts is easy. It is really easy. echo %str% set str = %str:is = % echo %str%

    The key thing to note about the above program is, the ‘is’ word is being removed from the string using the :’stringtoberemoved’ = command.

    Output

    The above command produces the following output.

    Batch scripts is easy. It is really easy. Batch scripts easy. It really easy.
     

     

     

     

     

    Example

    @echo off 
    set str = This string    has    a  lot  of spaces 
    echo %str% 
    
    set str=%str:=% 
    echo %str%

    The key thing to note about the above program is, the : = operator is used to remove all spaces from a string.

    Output

    The above command produces the following output.

    This string    has    a  lot  of spaces
    Thisstringhasalotofspaces
    

 

 

 

 

 

 

Example

@echo off 
set str=This message needs changed. 
echo %str% 

set str=%str:needs=has% 
echo %str%

The key thing to note about the above program is, the example replaces the word ‘needs’ with the string ‘has’ via the statement %str:needs = has%

Output

The above command produces the following output.

This message needs changed. 
This message has changed.

 

 
 
 
 
 

Example

@echo off set str = This message needs changed. echo %str% set str = %str:~-8% echo %str%

The key thing to note about the above program is, the right hand of the string is extracted by using the ~-‘number of characters to extract’ operator.

Output

The above command produces the following output.

This message needs changed. changed.
 

 

 

 

 

Batch Script - Variables

 

There are two types of variables in batch files. One is for parameters which can be passed when the batch file is called and the other is done via the set command.

Command Line Arguments

Batch scripts support the concept of command line arguments wherein arguments can be passed to the batch file when invoked. The arguments can be called from the batch files through the variables %1, %2, %3, and so on.

The following example shows a batch file which accepts 3 command line arguments and echo’s them to the command line screen.

@echo off 
echo %1 
echo %2 
echo %3

If the above batch script is stored in a file called test.bat and we were to run the batch as

Test.bat 1 2 3

Following is a screenshot of how this would look in the command prompt when the batch file is executed.

Command Line Arguments

The above command produces the following output.

1 
2 
3

If we were to run the batch as

Example 1 2 3 4

The output would still remain the same as above. However, the fourth parameter would be ignored.

 

Set Command

The other way in which variables can be initialized is via the ‘set’ command. Following is the syntax of the set command.

Syntax

set /A variable-name=value

where,

  • variable-name is the name of the variable you want to set.

  • value is the value which needs to be set against the variable.

  • /A – This switch is used if the value needs to be numeric in nature.

The following example shows a simple way the set command can be used.

Example

@echo off 
set message=Hello World 
echo %message%
  • In the above code snippet, a variable called message is defined and set with the value of "Hello World".

  • To display the value of the variable, note that the variable needs to be enclosed in the % sign.

Output

The above command produces the following output.

Hello World

Working with Numeric Values

In batch script, it is also possible to define a variable to hold a numeric value. This can be done by using the /A switch.

The following code shows a simple way in which numeric values can be set with the /A switch.

@echo off 
SET /A a = 5 
SET /A b = 10 
SET /A c = %a% + %b% 
echo %c%
  • We are first setting the value of 2 variables, a and b to 5 and 10 respectively.

  • We are adding those values and storing in the variable c.

  • Finally, we are displaying the value of the variable c.

The output of the above program would be 15.

All of the arithmetic operators work in batch files. The following example shows arithmetic operators can be used in batch files.

@echo off 
SET /A a = 5 
SET /A b = 10 
SET /A c = %a% + %b% 
echo %c% 
SET /A c = %a% - %b% 
echo %c% 
SET /A c = %b% / %a% 
echo %c% 
SET /A c = %b% * %a% 
echo %c%

The above command produces the following output.

15 
-5 
2 
50 
 
 

Local vs Global Variables

In any programming language, there is an option to mark variables as having some sort of scope, i.e. the section of code on which they can be accessed. Normally, variable having a global scope can be accessed anywhere from a program whereas local scoped variables have a defined boundary in which they can be accessed.

DOS scripting also has a definition for locally and globally scoped variables. 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. The following example shows the difference when local and global variables are set in the script.

Example

@echo off set globalvar = 5 SETLOCAL set var = 13145 set /A var = %var% + 5 echo %var% echo %globalvar% ENDLOCAL

Few key things to note about the above program.

  • The ‘globalvar’ is defined with a global scope and is available throughout the entire script.

  • The ‘var‘ variable is defined in a local scope because it is enclosed between a ‘SETLOCAL’ and ‘ENDLOCAL’ block. Hence, this variable will be destroyed as soon the ‘ENDLOCAL’ statement is executed.

Output

The above command produces the following output.

13150 5

You will notice that the command echo %var% will not yield anything because after the ENDLOCAL statement, the ‘var’ variable will no longer exist.

Working with Environment Variables

If you have variables that would be used across batch files, then it is always preferable to use environment variables. Once the environment variable is defined, it can be accessed via the % sign. The following example shows how to see the JAVA_HOME defined on a system. The JAVA_HOME variable is a key component that is normally used by a wide variety of applications.

@echo off echo %JAVA_HOME%

The output would show the JAVA_HOME directory which would depend from system to system. Following is an example of an output.

C:\Atlassian\Bitbucket\4.0.1\jre
 

 

Batch Script - Commands

 

Example

@echo off 
ver

Output

The output of the above command is as follows. The version number will depend upon the operating system you are working on.

Microsoft Windows [Version 6.3.9600]
 
 
 
 
 

Example

@echo off assoc > C:\lists.txt assoc | find “.doc” > C:\listsdoc.txt

Output

The list of file associations will be routed to the file lists.txt. The following output shows what is there in the listsdoc.txt file after the above batch file is run.

.doc=Word.Document.8 .dochtml=wordhtmlfile .docm=Word.DocumentMacroEnabled.12 .docmhtml=wordmhtmlfile .docx=Word.Document.12 .docxml=wordxmlfile
 
 
 
 
 

Example

The following example shows how the cd command can be used in a variety of ways.

@echo off Rem The cd without any parameters is used to display the current working directory cd Rem Changing the path to Program Files cd\Program Files cd Rem Changing the path to Program Files cd %USERPROFILE% cd Rem Changing to the parent directory cd.. cd Rem Changing to the parent directory two levels up cd..\.. cd

Output

The above command will display the following output after changing to the various folder locations.

C:\Users\Administrator C:\Program Files C:\Users\Administrator C:\Users C:\
 
 
 
 

Example

@echo off Cls

Output

The command prompt screen will be cleared.

 

 

 

 

Example

The following example shows the different variants of the copy command.

@echo off
cd
Rem Copies lists.txt to the present working directory.
If there is no destination identified , it defaults to the present working directory.
copy c:\lists.txt
Rem The file lists.txt will be copied from C:\ to C:\tp location
copy C:\lists.txt c:\tp
Rem Quotation marks are required if the file name contains spaces
copy “C:\My File.txt”
Rem Copies all the files in F drive which have the txt file extension to the
current working directory copy
F:\*.txt
Rem Copies all files from dirA to dirB. Note that directories nested in dirA will not be copied
copy C:\dirA dirB

Output

All actions are performed as per the remarks in the batch file.

 

 

 

 

 

Example

The following example shows the different variants of the del command.

@echo off 
Rem Deletes the file lists.txt in C:\ 
del C:\lists.txt 
Rem Deletes all files recursively in all nested directories
del /s *.txt 
Rem Deletes all files recursively in all nested directories , but asks for the 
confirmation from the user first 
Del /p /s *.txt

Output

All actions are performed as per the remarks in the batch file.

 

 

 

 

 

Example

The following example shows the different variants of the dir command.

@echo off
Rem All the directory listings from C:\ will be routed to the file lists.txt
dir C:\>C:\lists.txt
Rem Lists all directories and subdirectories recursively
dir /s
Rem Lists the contents of the directory and all subdirectories recursively, one 
file per line, displaying complete path for each listed file or directory.
dir /s /b
Rem Lists all files with .txt extension.
dir *.txt
Rem Includes hidden files and system files in the listing.
dir /a
Rem Lists hidden files only.
dir /ah

Output

All actions are performed as per the remarks in the batch file.

 

 

 

 

 

Example

@echo off 
echo %DATE%

Output

The current date will be displayed in the command prompt. For example,

Mon 12/28/2015 
 
 
 
 
 

Example

The following example shows the different variants of the dir command.

Rem Turns the echo on so that each command will be shown as executed echo on echo "Hello World" Rem Turns the echo off so that each command will not be shown when executed @echo off echo "Hello World" Rem Displays the contents of the PATH variable echo %PATH%

Output

The following output will be displayed in the command prompt.

C:\>Rem Turns the echo on so that each command will be shown as executed C:\>echo on C:\>echo "Hello World" "Hello World" C:\>Rem Turns the echo off so that each command will not be shown when executed "Hello World" C:\Users\ADMINI~1\AppData\Local\Temp 

 

 

 

 

Example

@echo off 
echo "Hello World" 
exit

Output

The batch file will terminate and the command prompt window will close.

 

 

 

 

 

Example

@echo off 
md newdir 
cd newdir 
cd Rem “Goes back to the parent directory and create 2 directories” 
cd.. 
md newdir1 newdir1 
cd newdir1 
cd 
cd.. 
cd newdir2 
cd

Output

The above command produces the following output.

C:\newdir 
C:\newdir1 
C:\newdir2 
 
 
 
 
 
 

Example

@echo off md newdir cd newdir cd Rem “Goes back to the parent directory and create 2 directories” cd.. md newdir1 newdir1 cd newdir1 cd cd.. cd newdir2 cd

Output

The above command produces the following output.

C:\newdir C:\newdir1 C:\newdir2 

 

 

 

 

 

Example

The following example shows the different variants of the move command.

@echo off
Rem Moves the file list.txt to the directory c:\tp
move C:\lists.txt c:\tp
Rem Renames directory Dir1 to Dir2, assuming Dir1 is a directory and Dir2 does not exist. 
move Dir1 Dir2
Rem Moves the file lists.txt to the current directory.
move C:\lists.txt

Output

All actions are performed as per the remarks in the batch file.

 

 

 

 

 

Example

@echo off 
Echo %PATH%

Output

The value of the path variable will be displayed in the command prompt.

 

 

 

 

Example

@echo off 
pause

Output

The command prompt will show the message “Press any key to continue….” to the user and wait for the user’s input.

 

 

 

 

 

Example

@echo off 
prompt myprompt$G

The $G is the greater than sign which is added at the end of the prompt.

Output

The prompt shown to the user will now be myprompt>

 

 

 

 

 

Example

The following example shows the different variants of the rd command.

@echo off
Rem removes the directory called newdir
rd C:\newdir

Rem removes 2 directories
rd Dir1 Dir2

Rem Removes directory with spaces
rd "Application A"

Rem Removes the directory Dir1 including all the files and subdirectories in it rd /s Dir1
Rem Removes the directory Dir1 including all the files and subdirectories in it but
asks for a user confirmation first.
rd /q /s Dir1

Output

All actions are performed as per the remarks in the batch file.

 

 

 

 

 

Example

@echo off 
ren C:\lists.txt C:\newlists.txt

Output

The file lists.txt will be renamed to newlists.txt.

 

 

 

 

 

Example

@echo off 
REM This is a batch file

 :: This is comment





Example

@echo off
start notepad.exe

Output

When the batch file is executed, a new notepad windows will start.

 

 

 

 

 

Example

@echo off 
echo %TIME%

Output

The current system time will be displayed. For example,

22:06:52.87 
 
 
 
 
 

Example

@echo off TYPE C:\tp\lists.txt

Output

The contents of the file lists.txt will be displayed to the command prompt.

 

 

 

 

 

Example

@echo off 
VOL

Output

The output will display the current volume label. For example,

Volume in drive C is Windows8_OS 
Volume Serial Number is E41C-6F43 
 
 
 
 
 

Example

The following example shows the different variants of the attrib command.

@echo off Rem Displays the attribites of the file in the current directory Attrib Rem Displays the attributes of the file lists.txt attrib C:\tp\lists.txt Rem Adds the "Read-only" attribute to the file. attrib +r C:\tp\lists.txt Attrib C:\tp\lists.txt Rem Removes the "Archived" attribute from the file attrib -a C:\tp\lists.txt Attrib C:\tp\lists.txt

Output

For example,

A C:\tp\assoclst.txt A C:\tp\List.cmd A C:\tp\lists.txt A C:\tp\listsA.txt A C:\tp\lists.txt A R C:\tp\lists.txt R C:\tp\lists.txt 

 

 

 

 

 

Example

@echo off 
chkdsk

Output

The above command starts checking the current disk for any errors.

 

 

 

 

 

Example

@echo off 
echo "What is the file size you what" 
echo "A:10MB" 
echo "B:20MB" 
echo "C:30MB" 
choice /c ABC /m "What is your option A , B or C"

Output

The above program produces the following output.

"What is the file size you what"
"A:10MB"
"B:20MB"
"C:30MB"
What is your option A , B or C [A,B,C]? 
 
 
 
 

Example

@echo off COMP C:\tp\lists.txt C:\tp\listsA.txt

Output

The above command will compare the files lists.txt and listsA.txt and find out if the two file sizes are different.

 

 

 

 

Example

@echo off 
FIND "Application" C:\tp\lists.txt

Output

If the word “Application” resides in the file lists.txt, the line containing the string will be displayed in the command prompt.

 

 

 

 

Example

@echo off 
FC lists.txt listsA.txt

Output

The above command will display the differences in the contents of the files (lists.txt and listsA.txt ) if any.

 https://ss64.com/nt/fc.html

 fc /b %Default_FILE% %NEW_DRIVE%\default_test.txt > nul && (

echo "The file is same default_test.txt %Default_FILE%"

) || (

echo %NEW_DRIVE%\default_test.txt

echo "%Default_FILE%"

copy /Y %Default_FILE% %NEW_DRIVE%\default_test.txt

echo "%Default_Startup_FILE%"

copy /Y %Default_Startup_FILE% %NEW_DRIVE%\startup.nsh

)

 

 

Example

@echo off 
Title “New Windows Title”

Output

The above command will change the title of the window to “New Windows Title”.

 

 

 

 

Example

@echo off 
set

Output

The above command displays the list of environment variables on the current system.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

2024年3月22日 星期五

Ubuntu 22.04上運行SSH服務器設定

 

安裝

  1. 輸入sudo apt install openssh-server -y
  2. 輸入sudo systemctl enable ssh開啟開機啟動
  3. 輸入sudo systemctl start ssh

允許防火牆

  1. 輸入sudo ufw allow ssh
  2. 輸入sudo ufw enable
  3. 輸入sudo ufw status

此時已能使用密碼登入

RSA金鑰

Client端

  1. 輸入mkdir -p $HOME/.ssh建立存放金鑰的檔案
  2. 輸入chmod 0700 $HOME/.ssh設定權限
  3. 輸入ssh-keygen -t rsa -b 4096 -C "my key for ubuntu server"產生金鑰
  4. 按Enter到底
  5. 輸入ssh-copy-id -f <ssh-server-account>@<ssh-server-ip>將公鑰送到SSH Server

Server端

  1. 輸入sudo nano /etc/ssh/sshd_config
  2. 找到參數PasswordAuthentication將其修改成以下
1
PasswordAuthentication no
  1. 輸入sudo systemctl restart ssh
  2. 完成

後記:轉移金鑰

  • 取出~/.ssh/id_rsa
  • 將檔案打開最後按一個Enter再存檔,不然會出現錯誤invalid format
  • 輸入ssh -i ./id_rsa ubuntu@192.168.1.102,就能成功連線
  • 完成

 

 資料來源:https://astroicers.link/p/%E5%9C%A8ubuntu-22.04%E4%B8%8A%E9%81%8B%E8%A1%8Cssh%E6%9C%8D%E5%8B%99%E5%99%A8%E9%9D%9E%E5%B8%B8%E5%AE%B9%E6%98%93.html



Ubuntu 安裝與設定 ssh server

要安裝 ssh server, 以下兩行指令都可以

# apt-get install ssh
# apt-get install openssh-server

安裝後可以修改一些 ssh 的設定, 如port, 密碼認證, root登入等

# vim /etc/ssh/sshd_config
Port 22
PasswordAuthentication yes
PermitRootLogin yes -> 是否開放 root 登入
更改完存檔後記得重啟服務
# /etc/init.d/ssh restart
資料來源https://www.nc.com.tw/modules/answer/question/44?srsltid=AfmBOoqLrjlq31HYhqLp3T0Nj07i2FNUa8adDFcCZht3m1lWpYJO0HjA