ls/usr/bin/The info# path Operation dirnamebasename# "" and "and" in the shell variable "" allows references to other variables by means of "" prohibit reference to other variables, as ordinary characters ' output of the command execution to the variable #执行一个命令, but does not protect the existence In the command history<space>Commandman ASCII #并行执行的命令之间添加&, multiple commands can be executed in parallel. LS& Echo'aaaaaaaa'& Echo'FESFSFSE'#串行执行命令 "&& ". If you want to see how long a program executes, you can use the command date&&./the program you need to execute &&date to view #shell1&& Shell2, if it is connected with a &&, it will only be executed when Shell1 returns 0 (that is, normal), otherwise shell2 is not executed at all, so the last cd&& This practice of RM is feasible and safe. that | | , for shell1| |Shell2, the SHELL2 executes only if the shell1 fails, otherwise shell2 is not performed frequently. forLoop {#for循环a="a b c d E F" forXinch$a; DoEcho $x +'Q'; Done forXinch{1..9}; Doecho $x; forXinch' Seq -`; Doecho $x;SelectAinch 1 2 3 4 5 6 7; Doecho $a; done #创建选择菜单, infinite loop sh-v install.sh #查看执行的代码sh-n install.sh #语法检查, no error does not display content F=/home/Config.ini whileRead-r b; DoEcho $b +'Dada'; Done <"$f"#一行一行读取文件 whileRead B; DoEcho $b +'Dada'; Done <$f whileRead B; DoEcho"your input is $b"; done #读入键入的内容cat1. txt | whileRead line; Doecho $line; done #读取文件 forXinch' Cat1. txt '; Doecho $x; done #按空格和回车读取文件}done&#后台执行循环echo $SHELL #查看当前环境所使用的shell解释器 # Script General first behavior: #!/bin/Bashchsh-L #查看系统支持哪些shell解释器
Whereis ls # The directory of the Find command which # View the path of the currently executing command echo-N123456|md5sum # MD5 Encryption VI/etc/hosts # query static hostname alias # alias Vmstat1 9# Report System performance information every second 9 times PS aux|grep-v USER | Sort-nk +4| Tail # shows the 10 running processes that consume the most memory, sorted by memory usage. CPU +3uname-A # View Linux kernel version information stty common commands used to change and print terminal line settings>Password Read-TTenVarName # The easier way is to use the Read command-T option iptables-F # Clears the rule entries from the firewall/etc/init.d/SendMail Start # Startup service/etc/init.d/SendMail Stop # Shutdown service/etc/init.d/sendmail Status # View the current status of the service/date/mysql/bin/mysqld_safe--user=mysql &# start MySQL background run VI/etc/rc.d/script. Sh # Start-up execution can be used for boot-up scripts/etc/rc.d/rc3.d/s55sshd # boot up and shut down service connection # s on start K shutdown Stop 55-level followed by service name Rsync-avzp-e"ssh-p"/dir [email protected] $IP:/dir # Sync Directory #--Delete no difference sync Delete directory under other files ifconfig eth0:0 192.168.1.221Netmask255.255.255.0# Add logical IP address to MTR-r www.baidu.com # Test network link node response time # Trace ping combined with echo1>/proc/sys/net/ipv4/Icmp_echo_ignore_all # Forbidden Pingipcalc-M"$ip"-P"$num"# Compute the mask SSH based on IP and host maximum number-P A[Email protected]192.168.1.209CMD # Remote host SCP with SSH operation-P Afile [email protected]:/Directory # Copy Local files to remote host SCP-R [email protected]192.168.1.209: Remote directory Local Directory # Copy remote specified files to local sshpass-P'Password'ssh-n [email protected] $IP"echo Hello"# Specify password remote operation SSH-O stricthostkeychecking=no $IP # SSH connection does not prompt yesdu-H Catalog # detects all file sizes in the directory du-sh *# Displays the size of the subdirectory in the current directory # bird finishing LS-L--full-Time #显示具体时间ls--full-time resource/LANG=en_US #修改诧系ls-R resource/#递归显示users # Show all logged-in Users groups # lists the current user and the group he belongs to-Q # Show all logged-in Users Groupadd # Add Group useradd User # Build users passwd User # Change Password chown-r User:group # Modify directory owner (R recursion) chown Y\.li:mysql # Modify owner user contains points"."umask # Set user files and directories for file creation default masking value CHGRP # Modify user group Finger # Find user display information echo"Xuesong"| passwd User--stdin # non-interactive change password Useradd-G www-m-s/sbin/Nologin www # Specifies that the group does not allow users to log on, Nologin allows the use of services Useradd-G www-m-s/bin/falsewww # Specifies that the group does not allow users to log on, false is the most stringent usermod-L new user name old username # Modify user name Usermod-G User Group # Modify user-owned group Usermod-D Directory-m User # Modify user home directory Usermod-G Group User # adds users to the additional group GPASSWD-d User Group # Remove the user Su from the group-User-c"#命令1;"# Toggle User Execution
Script {#!/bin/sh # in script first line script header # SH for current system default shell, can be specified as bash etc shellsh-x # execution procedure Sh-n # Check Syntax (A=BBK) # parentheses Create child Shell run BASENAME/A/B/C # from full The path retains the last layer of file name or directory dirname # Fetch path $random # random number $$ # process number source FileName # reads and executes the command # equivalent in the FileName in the current bash environment. Filenamesleep 5 # Interval sleep 5 Seconds trap # The action to be taken after receiving the Signal trap "2 3 # Forbidden Ctrl+c$pwd # current directory $home # home directory $oldpwd # before a directory path CD-# Back to the previous directory Path local RET # local variable Yes # repeat print Yes |rm-i * # Auto answer y or other ls-p/home # View directory all folders ls-d/home/# view match full path echo ' ls ' #执行 lsecho-n a A;echo BB # does not wrap to execute the next sentence to output the string as is Echo-e "s\tss\n\n\n" # makes escape effective echo $a | Cut-c2-6 # takes a character in a string echo {a,b,c}{a,b,c}{a,b,c} # permutation combination (one element in parentheses and other elements in parentheses) echo $ ((2#11010)) # Binary to 10 binary echo AAA | Tee File # Print Write file default overwrite-a append echo {1..10} # Print 10 characters printf '%10s\n ' |tr "" A # Print 10 characters pwd | awk-f/' {print $} ' # return directory name tac file |sed 1,3d|tac # Read the file upside down # Delete the last 3 lines tail-3 file # take the last 3 lines outtmp=/tmp/$$ ' Date +%s%n '. Outtm P # temp file definition: () {:|:&};: # Famous Fork bomb, System executes massive process until system zombie ECHO-E "\e[32m....\e[0m" # Print color Echo-e "\033[0;31ml\033[0;32mo\0 33[0;33mv\033[0;34me\t\033[0;35my\033[0;36mo\033[0;32mu\e[m "# Print color
Variable {a= "A b C def" # Copy string to variable a= ' cmd ' # assigns command result to variable a=$ (CMD) # Assigns command result to variable eval a=\$ $a # Indirect call I=2&&echo $ ((i+3)) # Print new variable after calculation Result I=2&&echo $[i+3] # Prints a new variable result a=$ ((2>6?5:8) # to determine that two values satisfy the assignment of the condition to the variable a= (a b C def) # defines the variable as the number of groups, the $ $ $* # positional parameter * represents all env # View Environment Variables env | grep "Name" # View defined environment variable set # View environment variable and local variable read name # input variable readonly name # set name to read-only variable, do not allow setting ReadOnly # See read-only file for System Presence Expo RT Name # variable name is promoted locally to environment export name= "RedHat" # directly defines name as environment variable export stat$nu=2222 # Variable reference variable assignment unset name # variable clear export-n name # Remove the read-only variable shift # to move the position variable, adjust the position variable, give the value of $ $2.$2 to the value assigned to $1name + 0 # Convert the string to the number "" # Convert the number to a string a= ' Ps-auxh|grep Node|awk ' {pri NT $ {} ' for x in SEQ $a; Do kill $x; Done #删除node的所有进程}
Declare-f #显示当前可见的所有函数declare-F #查看详细函数代码ifconfig网卡 {#网卡的常用命令ifconfig-a #查看所有网卡ifconfig eth85ifconfig eth85 Downifconfig eth85 up# on the ETH85 network port, configure the IP address to 156.41.50.11, the subnet mask 255.255.255.0 the ipifconfig eth85 156.41.50.11 netmask 255.255.255.0# Delete eth85 network port, IP address is 156.41.50.12, subnet mask is 255.255.255.0 ipip addr del 156.41.50.12/24 dev Eth85ifconfig eth1:0 10.175.102.123 netmask 255.255.252.0 up configuration floating ip# prevent restart failure in/etc/sysconfig/network directory, vi ifcfg-"NIC name" "MAC Address" example: ifcfg-eth1 IFCFG-E0:24:7F:B6:FD:1B Add IP information to the file and save the file bootproto= ' static ' startmode= ' auto ' ipaddr= ' 182.3.1.180 ' netmask= ' 255.255.0.0 ' Restart NIC to make IP effective rcnetwork restart eth5# sample bootproto= ' static ' broadcast= ' ipaddr= ' 192.121.1.71 ' netmask= ' 255.255.255.0 ' startmode= ' auto ' usercontrol= ' no ' firewall= ' no ' device=eth1} variable {#赋值时等号两边不能有空格 # when using a variable, precede the variable with the symbol $, But the scope of the variable is not required at the time of definition 1, variables that are not specially handled are variables defined in the global variables script that can be used anywhere else in the script. Note: Variables defined inside the function can also be used outside of the function. 2, you can use export to change the normal variable environment variables can be used by its child processes, and ordinary variables are not. Export $var 3, you can use local to define a local variable locally keyword can only be used inside the function. Variables defined with local can only be used in this function. #特殊变量有些变量是一开始执行Script时就会设定, have a specific meaning and cannot be modifiedOf These are system special variables: $ $n The name of the current script the nth parameter value of a script or function, the n=1..9$* of all parameters of a script or function $# the number of arguments to a script or function $$ the current shell process pid$! Pid$ of the last shell daemon process? Previous command return value other parameters: $CDPATH contains a list of directory names, and the CD command searches them to find the directory passed to it as a parameter, and if the variable is not set, the CD command searches the default editor used in the current directory $editor program (such as an e-mail program) $env The path of the UNIX lookup profile $home the name of the user's system mailbox file at the time of the initial logon $mail the user's mailbox $mailcheck the shell checks to see if the user has a new message and notifies the user of the result (in seconds) $PATH A variable that contains the user's search path-shell the directory used to search for an external command or program $ppid the process of the parent process id$ps1 The first prompt, typically a second prompt for the $PS 2 system, typically a > $PWD the name of the current working directory $term the type of the user's control terminal . $LINENO the line of code that is typically used to output the error line number shift [n] shifts the command-line parameter to the left n-bit, but does not change the export variable name table to pass the variables listed in the Variable name table to the child process read Variable name table from the standard input reading string, to the specified variable echo variable name table Displays variables specified by the variable name table to the standard output set display Set Variable env display all variables set command can reset parameter table. The set Hello Wold command sets $* as the string Hello World, $n and $ #也同时受影响. The shift command can move all parameters to the left one unit, $*, $n, $ #均受影响}
Array {1. Initialize #!/bin/bash #指定索引值 array1[0]=one array1[1]=1 echo ${array1[0]} echo ${array1[1]} #全数组初始化 array2= (one, one, three) echo ${array2[0]} echo ${array2[2]} #间隔索引 array3= ([9]=nine [11]=11] echo ${array3[9]} echo ${array3[11]} #读取键盘输入, spaces separated, newline End Read-a Array4 exit 02. Operation!/bin/bash Array= (Apple Bat cat Dog Elephant Frog) #打印第一个元素 echo ${array[0]} Echo ${array:0} #打印所有元素 echo ${array[@]}echo ${array[*]} echo ${array[@]:0} #除了第一个元素, print all elements echo ${array[@]:1} #从第二个元素开始, print four elements echo ${ar Ray[@]:1:4} #第一个元素的长度echo ${#array [0]} echo ${#array} #总元素数echo ${#array [*]} echo ${#array [@]} #将元素的a替换为A Echo ${array[@] A/A} exit 03. Traverse for I in "${array[@]}" do#access each element as $i ... do for x in ${b[@]};d o echo $x; Done4. Delete directly by: unset array [subscript] to clear the corresponding element. Echo ${varlist[*]}1 3 4 5 8unset varlist[7]echo ${varlist[*]}1 100 3 4 5 No subscript, clear entire data unset varlist}
Sed{sed-i ' s/cpu/lgj/' sys_info.txt #将修改生效到原文件常用sed的语法: 1. P: Print sed ' num1,num2p ' fileName #打印fileName中的num1到num2行2. S: replace string sed ' s/str1/str2/' fileName #把fileName中str1替换成str2 (replace only the first str1 in each row) 3. G: Global sed ' s/str1/str2/g ' fileName #把fileName中str1替换成str2 (replace All) 4. Y: Replace character sed ' y/abc/abc/g ' fileName #把fileName中所有的a替换成A, B is replaced by B, parameter-e: Executes a command. You can use the-e parameter to execute multiple commands at a time to improve efficiency sed–e ' Command1 ' –e ' command2 ' ... fileName #文件中的每一行执行命令: Command1 #command2 ... ^: Beginning of Line $ : End of line sed ' s/^str1/str2/' fileName #把fileName中每行开头的str1替换成str2sed –e ' s/^str1/str2/' –e ' s/str1$/str2/' FileName Some common scenarios introduced: 1. Line match sed-n ' 2p '/etc/passwd print out line 2nd sed-n ' 1,3p '/etc/passwd print out 1th to 3rd line sed-n ' $p '/etc/passwd print out last line sed-n '/user/' p/etc/ passwd prints a line containing user sed-n '/\$/' p/etc/passwd prints a line containing $ metacharacters, meaning the last line of 2. Insert text and append text (insert new line) Sed-n '/ftp/p '/etc/passwd print out an FTP line ftp:x:14:50:ftp user:/var/ftp:/sbin/nologinsed '/ftp/a\ 456 '/etc/ passwd inserts a row after the line containing the FTP, the content is 456sed '/ftp/i\ 123 '/etc/passwd a new row before the line containing the FTP, the content is 123sed '/ftp/i\ "123"/etc/ passwd inserts a row in front of the line containing the FTP, the contentFor "123" sed ' 5 a\ 123 '/etc/passwd insert a new line after line 5th, 123sed ' 5 i\ ' 12345 '/etc/passwd insert a new row before line 5th, with the content "12345" 3. Delete text sed ' 1d '/etc/passwd delete line 1th sed ' 1,3d '/etc/passwd delete line 1th to 3rd sed '/user/d '/etc/passwd delete row with user sed-i '/^$/d ' ver_info.tx T #删除空行sed ' s/remote_gateway_hostname.*/remote_gateway_hostname=/' Config.ini #很有用4. Replace text, replace command replaces the specified pattern with a replacement pattern, in the form: [A D D r e s S [, address]] s/pattern-to-find/replacement-pattern/[g p w n]sed ' s/user/user/'/ ETC/PASSWD replaces the 1th user with User,g to indicate that the global replacement sed ' s/user/user/g '/etc/passwd replace all user with usersed ' s/user/#user/'/etc/passwd Replace the 1th user with #user, such as the sed ' s/user//'/etc/passwd for shielding action, and replace the 1th user with the null sed ' s/user/&11111111111111/'/etc/passwd If you want to attach or modify a very long string, you can use the (&) command,& command to save the discovery mode to recall it, and then put it inside the replacement string, here is the & put forward sed ' s/user/11111111111111&/' /etc/passwd here is to put & back 5. Quick Line command The following is a set of one-line commands. ([] denotes a space, [] denotes t a B key) ' s/\. $//G ' Delete with a period end line '-e/abcd/d ' remove the line containing a B c d ' s/[] [] [] */[] [] [] */[]/g ' Delete one to the sky, with a space instead of ' s/^ [] [] *//G ' Delete the beginning of the space ' s / \ . [] [] */[]/g ' Delete period followed by two or moreMultiple spaces, replaced by a space '/^ $/d ' Delete empty line ' s/^. //G ' Delete first character ' S/col \(...\)//g' delete immediately after C O L three letters ' s/^ \///G ' Remove the first ' s/[]/[]//g ' from the path and remove all spaces and replace with T a B key Substituting ' s/^ []//G ' delete line all t a B key ' S/[] *//G ' Delete all t a B key if the file is filtered using sed, it is a good idea to divide the problem into steps, step through it, and perform the edge test results. }
Cat{has three major functions: 1. Display the entire file at once. $ cat filename2. Create a file from the keyboard. $ cat > FileName <<QQQQ create fiename file, append content, when encountered QQ end input can only create new files, cannot edit existing files. 3. Merge several files into one file: $cat file1 file2 > Filecat-n Config.ini Display line number}cut{cut [-bn] [file] or cut [-c] [file] or cut [-DF] [file] Use the description Cut command to cut bytes, characters, and fields from each line of the file and add those bytes, character, and The field is written to standard output. If you do not specify a File parameter, the Cut command reads standard input. One of the-B,-C, or-f flags must be specified. Main parameter-B: Split in bytes. These byte locations will ignore multibyte character boundaries unless the-n flag is also specified. -C: Split in characters. -D: Custom delimiter, default is tab. -F: Used with-D to specify which area to display. -N: Cancels splitting multibyte characters. Used only with the-B flag. If the last byte of the character falls within the range of <br/> indicated by the List parameter of the-B flag, the character will be written out, otherwise the character will be excluded from the # instance $ cat/etc/passwd | Tail-n 5 | Cut-d:-F 1postfixapacheicecreammysqlnews}du{Look at the size of the directory-S displays the final results--------in m displays-K in K in units Display-H in the appropriate units for common use: DU–HS./*}
#!/usr/bin/expect-fif {$ARGC < 2} {#打印 puts stdout "$ARGV 0 Err params\n" Exit 1} #行后面不可以加注释 # define function proc Do_console_logi n {Login Pass} {puts $login;p UTS $pass;} #打印参数长度puts [llength $argv] #设置变量 #set timeout-1 Set expect never timeout set timeout 5 #设置超时时间set user [lindex $argv 0] #获取脚本运行时带的第一个参数 Value set password [lindex $argv 1] #调用函数do_console_login $user $passwordspawn ssh [email protected] #判断上次输出结果里是否包含 " Password: "The string, if any, returns immediately, otherwise it waits for a period of time to return, waiting for the length of the previous set of 10 seconds. #开始匹配后, it is not possible to annotate expect {"(yes/no) in the back of the line." {send "yes\r" expect "Password:" send "$password \ r" Exp_continue} "*assword" {send "$password \ r" Exp_continue}}######### # puts will put all the prints together ############ #遍历的几种方法: foreach I {1 3 5 7 9} {puts "$i"} #i默认增量是1, i.e. equivalent incr i 1puts "---1---" for {set I 0} {$i < 3} {INCR i} {puts "I inside first loop: $i"}puts "---2---" for {set I 3} {$i < 2} {incr i} {puts "I inside second loop: $i"}puts "-- -3---"Set i 0while {$i < 4} {puts" I inside third loop: $i "incr iputs" I after incr: $i "}set i 0incr iputs"---4---"put S "$i"#expect里的加减法set I [Expr {$i + 1}] puts "---5---" puts "$i" #替代手工输入, execute the command with each command separated by a space! If {1 eq 1} {puts "Sync complete!"} else {puts "Sync error!"} #if usage Set File "/usr/lgj" if {[File isfile $File]!=1} {send_user "$argv 0:file $File not found." Send_user "mkdir $File \ n" Send "cd/usr/\r mkdir $File \ n" send "CD lgj\n touch 11.log\r"}send_user "for use\n" Send_user "rea D file as print\n "################ #打开原主机中的文件在登陆机上打印 ############### #set fd [open"./test.sh "" R "]set number 0# read each Li Newhile {[Gets $fd line] >= 0} {incr number #puts "Number of lines: $number" puts $line}send_user "read file as cmd\n" C Lose $FD ################ #打开原主机中的文件作为shell命令行在登陆机上执行 # # # #set FD [Open]]set number 0while {[Gets $fd line] &G T;= 0} {incr number send "$line \ n"}close $fdputs "do next!"; #把控制权交给控制台, this time can be manually operated interact
Linux Shell Summary