Windows Batch VS Linux Shell

advertisement
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
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 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
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
find (file)
/findstr(stri
ng in 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
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 help
MS-DOS
Linux / Unix
help
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.com
http://www.ss64.com
http://www.robvanderwoude.com
External commands
Windows
Linux / Unix description
ping
ping
shutdown
shutdown
sleep
sleep
ipconfig
ifconfig
Zip/unzip/ gzip/7zip
robocopy
Test internet connection.
Turn off or reboot the machine.
Delay for a specified time
Displays or changes internet information.
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
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 variables
Windows
Linux/Unix
Set Name = Value
Set path = Name;%PATH%
Echo %path%
Name=Value
PATH=Name:$PATH
Echo $PATH
set
;
:
No spaces
Case Sensitive
%Name%
$Name
readonly
Environment variables
windows
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
Linux
call
Source (sh中可以使用dot command即.shell file
name)
Start
Sh filename (sh filename &)
Setlocal/endlocal
Export
Special signs
Windo
ws
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 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-CONSEQUENTCOMMANDS;
fi
Label/goto/function
Windows batch
Linux shell
@echo off
function FUNCTION { COMMANDS; }
或者
FUNCTION () { COMMANDS; }
echo 调用前
echo 调用子过程
call :sub
echo 调用后
Goto end
:sub
echo 子过程调用中
goto :eof
:end
echo 退出
Pause
exit
调用 FUNCTION arguments
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
LinuxUntil/while/case/break/continue
• while CONTROL-COMMAND; do CONSEQUENTCOMMANDS; done
• until TEST-COMMAND; do CONSEQUENTCOMMANDS; done
• case EXPRESSION in CASE1) COMMAND-LIST;;
CASE2) COMMAND-LIST;; ... CASEN) COMMANDLIST;; esac
• select WORD [in LIST]; do RESPECTIVECOMMANDS; 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
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
Download