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_(computin g)
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_wi ndows_and_linux
Same internal commands MS-DOS /Linux / Unix description echo set date time cd more exit pushd popd Displays messages. Displays environment variables. Displays or sets the date. Displays or sets the system time. Displays the name of the current directory. Display the content in several pages Exit dos or shell external. Saves the current directory then changes it. Restores the previous value of the current directory saved by pushd.
Different internal commands MS-DOS Linux / Unix descriptions cls 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 del /rd /erase move /ren / rename cp rm mv Copies one or more files to another location. Deletes one or more files. md /mkdir mkdir Creates a directory. Moves one or more files from one directory to another directory. cd pwd Displays the name of the current directory. find /findstr(stri ng in file) find (file) Searches for a text string in a file or files. Searches for a file in a directory.
Other internal Commands MS-DOS Linux / Unix descriptions at Schedules commands and programs to run on a computer. comp / fc ver / cmd tree subst assoc Compares the contents of two files or sets of files. Displays the Windows version. Graphically displays the directory structure of a drive or path. Associates a path with a drive letter. Displays or modifies file extension associations. chmod chown Change access permissions Change file owner and group tasklist ps Process status task kill kill Stop a process from running who whoami Print all usernames currently logged in Print the current user id and name
Command help MS-DOS help help command-name Linux / Unix help command-name -help Command-name /? whatis command-name whereis command-name man command-name Info command-name type command-name http://www.computerhope.com http://www.ss64.com http://www.robvanderwoude.com
External commands Windows 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 robocopy Compress or uncompress files. 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 Shell Windows.bat /.cmd Linux/Unix.sh /.ksh /.bash /.csh/.tcsh #!/bin/sh @echo off Bash x filename.sh Rem (::) # chmod a+x filename filename./filename
Environment variables Windows Set Name = Value Set path = Name;%PATH% Echo %path% set ; : %Name% Linux/Unix Name=Value PATH=Name:$PATH Echo $PATH No spaces Case Sensitive $Name readonly
windows Environment variables 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 variables windows linux replace %VariableName:ReplacementString=Origin alstring% 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="thisisaverylongn ame" 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 call Start Setlocal/endlocal Linux Source (sh 中可以使用 dot command 即.shell file name) Sh filename (sh filename &) Export
Windo ws linux & & command1 & command2 Special signs 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 caculation windows SET /A variable = Expression set /a var=5+2 set /a var=55*34 set /a var=55/34 set /a var=55%%34 set /a var= (8+(9/3+7))*3 但 set /a vat=55.1*34 是错误的, 因为批处理不支持浮点运算 SET /A x = 1 SET /A y = 2 SET /A z = x + y + 3 ECHO z a=2 c=5 let b=$a*$c echo $b $((i++)) $((3 > 2)) $(( (3 > 2) (4 <= 1) )) declare -i val3=12 val4=5 declare -i result2 result2=val3*val4 echo $result2
Error status windows 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/else 变量延迟 windows IF [NOT] EXIST filename command IF EXIST filename. ( del filename. ) ELSE ( echo filename. missing. ) if TEST-COMMANDS; then CONSEQUENT-COMMANDS; fi 如果 TEST-COMMANDS 结果是 0, 则执行 then 中的语句 if TEST-COMMANDS; then CONSEQUENT-COMMANDS; elif MORE-TEST-COMMANDS; then MORE-CONSEQUENT-COMMANDS; else ALTERNATE-CONSEQUENT- COMMANDS; fi
Label/goto/function Windows batch @echo off echo 调用前 echo 调用子过程 call :sub Linux shell function FUNCTION { COMMANDS; } 或者 FUNCTION () { COMMANDS; } 调用 FUNCTION arguments echo 调用后 Goto end :sub echo 子过程调用中 goto :eof :end echo 退出 Pause exit
For FOR %variable IN (set) DO command [commandparameters] 在批处理程序中使用 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 %%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 ) for NAME [in LIST ]; do COMMANDS; done
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/python can work in different os; more powerful; but complex;
Shell and batch references http://technet.microsoft.com/zhcn/library/cc758944(ws.10).aspx http://www.arachnoid.com/linux/shell_progra mming.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
Thanks Q&A
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