Windows Batch VS Linux Shell
Jason Zhu
Agenda
• System and Shell• Windows batch and Linux Shell– Dos and Linux Shell internal Commands– Windows and Linux external commands– Batch and Shell variable and special sign– Batch and Shell Key words
• build forge VS batch/shell• Batch/Shell VS Perl/python
System history
Shell history
• Shell: a piece of software that provides an interface for users
• Unix/Linux: Bourne/Korn/C/Tc/Bash• Linux GUI: Gnome,kde,xfce• Windows: cmd.exe/explorer.exe• http://en.wikipedia.org/wiki/Shell_(computing
)
The difference of Windows and Linux
• Case sensitive in Linux• / in Linux• No relationship between executable file and
extension• don't search current path• Security policy is more strict in Linux• link file VS shortcut• http://en.wikipedia.org/wiki/Comparison_of_
Windows_and_Linux
Same internal commandsMS-DOS /Linux / Unix description
echo Displays messages.
set Displays environment variables.
date Displays or sets the date.
time Displays or sets the system time.
cd Displays the name of the current directory.
more Display the content in several pages
exit Exit dos or shell external.
pushd Saves the current directory then changes it.
popd Restores the previous value of the current directory saved by pushd.
Different internal commandsMS-DOS Linux / Unix descriptionscls clear Clears the screen.
dir ls Displays a list of files and subdirectories in a directory.
type cat Displays the contents of a text file.
attrib chmod Displays or changes file attributes.
copy / xcopy
cp Copies one or more files to another location.
del /rd/erase
rm Deletes one or more files.
move /ren/ rename
mv Moves one or more files from one directory to another directory.
md /mkdir mkdir Creates a directory.
cd pwd Displays the name of the current directory.
find /findstr(string in file)
find (file) Searches for a text string in a file or files. Searches for a file in a directory.
Other internal CommandsMS-DOS Linux / Unix descriptionsat Schedules commands and programs to run on a computer.
comp / fc Compares the contents of two files or sets of files.
ver / cmd Displays the Windows version.
tree Graphically displays the directory structure of a drive or path.
subst Associates a path with a drive letter.
assoc Displays or modifies file extension associations.
chmod Change access permissions
chown Change file owner and group
tasklist ps Process status
task kill kill Stop a process from running
who Print all usernames currently logged in
whoami Print the current user id and name
Command helpMS-DOS Linux / Unixhelp help
help command-name command-name -help
Command-name /?
whatis command-name
whereis command-name
man command-name
Info command-name
type command-name
http://www.computerhope.comhttp://www.ss64.com
http://www.robvanderwoude.com
External commandsWindows Linux / Unix description
ping ping Test internet connection.
shutdown shutdown Turn off or reboot the machine.
sleep sleep Delay for a specified time
ipconfig ifconfig Displays or changes internet information.
Zip/unzip/ gzip/7zip Compress or uncompress files.
robocopy Copy files or directory robustly.
printf printf Format and print data.
expr expr Evaluate expressions
sed sed Stream editor for filtering and transforming text. (replace and delete)
awk awk AWK is a programming language that is designed for processing text-based data, either in files or data streams.
grep grep Print lines matching a pattern.
Where to get more useful tools
• http://unxutils.sourceforge.net/• ftp://ftp.microsoft.com/reskit/• http://www.microsoft.com/mspress/windows
server2003reskit/• http://live.sysinternals.com/• http://www.nirsoft.net• Other such as zip/unzip…
Robocopy(windows)• windows copy/xcopy:• copy “c:\new folder\1.txt” c:• copy “c:\new folder\1.txt” c:\2.txt
• Linux cp/windows cp.exe• cp ~/a.txt ~/test (cp c:\1.txt c:\test2)• cp ~/a.txt ~/test/b.txt (cp c:\1.txt c:\3.txt)
• Windows robocopy:• robocopy /E /NP /R:12 /w:10 /MIR SourceDir DestinationDir *.txt *.doc /XF
test.txt /xd test• Must check the return value
Printf(windows/Linux)
• Printf • Printf %3d 2• printf %-3d 2• Printf %03d 2• Printf %1.2f 3.1415926• printf %8s "aaaa"• printf "\nSubDoc: %03d\n" 3
Expr(windows/Linux)• expr 5 + 7 expr 5 – 6• expr 5 ”*” 4 expr 5 / 7• expr 7 % 9 • expr 1 “|” 0 expr 1 “&” 0 • expr 3 “>” 6 expr 3 “<” 6 • expr 3 “>=” 3 expr 3 “<=” 3 • expr 3 = 3 expr 3 != 3 • expr expr1 : re expr index expr1 expr2 • expr substr expr1 expr2 expr3 • expr length "abcdef"• expr length "abcdef" "<" 5 "|" 15 - 4 ">" 8
Awk(windows/Linux)
• awk '{print $0}' scores.txt• awk '{if($2 ^> "60") print $0}' scores.txt• awk 'BEGIN {print "start..."} {tot+=$2} END
{print "totoal is:" tot; print "END..."}' scores.txt• awk '{print length($2)}' scores.txt
sed
• sed [ 选项 ] s e d 命令 输入文件。• sed = test3.txt• sed s/mapguide/mapguide2010/g test3.txt• sed 5,6d test3.txt• sed 3a\abcd test3.txt• sed 10i\adflajflad\n\adfadfajdlf test3.txt• Sed 10c\aaaa test3.txt• sed 4q test3.txt• sed 2r 1.txt test3.txt
grep
• grep "map" test4.txt• grep "map" *.txt• grep -c “aud“ test4.txt• grep -n “aud“ test4.txt• grep -v “aud“ test4.txt• grep -i “aud“ test4.txt
Batch VS ShellWindows Linux/Unix
.bat / .cmd .sh / .ksh / .bash /.csh/.tcsh …
#!/bin/sh
@echo off Bash –x filename.sh
Rem (::) #
chmod a+x filename
filename ./filename
Environment variablesWindows Linux/Unix
Set Name = ValueSet path = Name;%PATH%Echo %path%
Name=ValuePATH=Name:$PATHEcho $PATH
set
; :
No spaces
Case Sensitive
%Name% $Name
readonly
Environment variableswindows linux
%* $* Lists all the arguments that have been passed to the script
%0 $0 Stores the name of the script
%1~9 $1~9 Stores the first to ninth argument passed to the script
$# The number of arguments
$$ The current process id
$! The last background process id
If parameters include blank spaces, you would need to surround both file names with double quotes before passing them to your script
shift
Environment variableswindows linux
replace %VariableName:ReplacementString=OriginalString%set a=belcome to CMD borld! set temp=%a:b=w% echo %temp% pause 将显示 welcome to CMD world! 即用 w替换了变量 a 中的 b 。
${VAR/PATTERN/STRING} or ${VAR//PATTERN/STRING} 语法。第一种形式仅仅替换第一个匹配的项目,第二个用 STRING 替换所有匹配 PATTERN 的项目。
substr %VariableName:~StartPosition,Length%set a=superhero set temp=%a:~0,-3% echo %temp% pause 将显示 superh 即显示了变量 a 的第 0 位和第 -3 位中间包含的所有字符。
${varname:offset:length} Purpose: Returning parts of a string (substrings or slices).STRING="thisisaverylongname" echo ${STRING:6:5}
Linux 参数变量• a. 变量 =${ 参数 -word} :如果设置了参数,则用参数的值置换变量的值,否则用 word 置换。即这种变量的值等于某一个参数的值,如果该参数没有设置,则变量就等于 word 的值。• b. 变量 =${ 参数 =word} :如果设置了参数,则用参数的值置换变量的值,否则把变量设置成 word ,然后再用 word 替换参数的值。注意,位置参数不能用于这种方式,因为在 Shell 程序中不能为位置参数赋值。• c. 变量 =${ 参数? word} :如果设置了参数,则用参数的值置换变量的值,否则就显示 word 并从 Shell 中退出,如果省略了 word ,则显示标准信息。这种变量要求一定等于某一个参数的值。如果该参数没有设置,就显示一个信息,然后退出,因此这种方式常用于出错指示。• d. 变量 =${ 参数 +word} :如果设置了参数,则用 word 置换变量,否则不进行置换。
Call/start/source/sh
Widnwos Linux
call Source (sh 中可以使用 dot command 即 .shell file name)
Start Sh filename (sh filename &)
Setlocal/endlocal Export
Special signsWindows
linux
& & command1 & command2
Runs the first command followed by the second command
| | Comand1 | command2 The result of the first comand will be as input of the second command
&& && command && command
Runs the second command if the first command was successful
|| || command || command Runs the second command if the first command had an error
> > Echo “hello” > file.txt Transfer and overwrite>> >> Type file1.txt >> file.txt Transfer and append< < command < command^ \ Disable the meaning of some special
signs, such as >,<,&…
:: # Comment, it is equal to REM
Expression caculationwindowsSET /A variable = Expressionset /a var=5+2 set /a var=55*34 set /a var=55/34set /a var=55%%34set /a var= (8+(9/3+7))*3但 set /a vat=55.1*34 是错误的,因为批处理不支持浮点运算。
a=2c=5let b=$a*$cecho $b
$((i++))
$((3 > 2)) $(( (3 > 2) || (4 <= 1) ))
SET /A x = 1 SET /A y = 2 SET /A z = x + y + 3 ECHO z
declare -i val3=12 val4=5declare -i result2result2=val3*val4echo $result2
Error statuswindows Linux
errorlevel $?
2> file : Sends all error output to a file or device
2>&1 : Sends all error output to the same location as all normal output
文件描述符通常是 :STDIN,STDOUT,STDERR, 即 :0,1,2, 由此可以看出 , 它将command 在输出过程中产生的错误信息也放在了 STDOUT 。Standard Input. The location where the Windows shell looks for command input. By default, this is the computer's keyboard.Standard Output. The default location where the Windows shell sends all output. By default, this is the Windows command console.Standard Error. The default location where the Windows shell sends all error messages. By default, this is the Windows command console.
If/then/elsewindows
IF [NOT] EXIST filename commandif TEST-COMMANDS; then CONSEQUENT-COMMANDS; fi 如果 TEST-COMMANDS 结果是0 ,则执行 then 中的语句。
IF EXIST filename. ( del filename. ) ELSE ( echo filename. missing. )
if TEST-COMMANDS; then CONSEQUENT-COMMANDS; elif MORE-TEST-COMMANDS; then MORE-CONSEQUENT-COMMANDS; else ALTERNATE-CONSEQUENT-COMMANDS; fi
变量延迟
Label/goto/functionWindows batch Linux shell
@echo off
echo 调用前 echo 调用子过程 call :sub
echo 调用后 Goto end
:sub echo 子过程调用中goto :eof
:endecho 退出Pause exit
function FUNCTION { COMMANDS; } 或者FUNCTION () { COMMANDS; }
调用 FUNCTION arguments
ForFOR %variable IN (set) DO command [command-parameters]在批处理程序中使用 FOR 命令时,指定变量请使用 %%variable 而不要用 %variable 。变量名称是区分大小写的,所以 %i 不同于 %I./l Sets up the loop to process a range of values /f Sets up the loop to process all elements stored within a string /d Sets up the loop to process all files stored within a specified folder /r Sets up the loop to process all subfolders stored within a specified parent folder
for NAME [in LIST ]; do COMMANDS; done
for %%i in (a b c d e f g h i ) do ( echo %%i ) for /l %%i in (1,1,100) do ( set /a var+=1 )
Linux- Until/while/case/break/continue
• while CONTROL-COMMAND; do CONSEQUENT-COMMANDS; done
• until TEST-COMMAND; do CONSEQUENT-COMMANDS; done
• case EXPRESSION in CASE1) COMMAND-LIST;; CASE2) COMMAND-LIST;; ... CASEN) COMMAND-LIST;; esac
• select WORD [in LIST]; do RESPECTIVE-COMMANDS; done
• Break/continue
Build Forge vs batch and shell
• variables definition : build forge syntax• Variables using: both of windows and Linux• Slashes: both of them are ok• For linux OS: shell syntax• For Windows OS: batch syntax
Batch and shell VS perl and python
• Shell simply and suitable for daily work
• Perl/pythoncan work in different os; more powerful; but complex;
Shell and batch references
• http://technet.microsoft.com/zh-cn/library/cc758944(WS.10).aspx
• http://www.arachnoid.com/linux/shell_programming.html
• http://www.freeos.com/guides/lsst/• http://linuxcommand.org/
Batch and shell books
• Microsoft Windows Shell Script Programming for the Absolute Beginner.chm
• 批处理阶段教程奥运最终版 [ 英雄出品 ]• Bash. 新手指南 . 中文版 .
(Bash.Beginners.Guide.CHS).CHM• Learning the bash Shell, 3rd Edition.chm• UNIX Shells by Example Fourth Edition.chm
Q&A
• Thanks
Interactive Input
windows
SET /P Var=[MessagePrompt] @echo off set /p input= 请输入! echo 您输入的是 %input% pause
Read -p PROMPT name
read year –p “input:“Echo 您输入的是 $year