In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/03 Report--
In my self-study shell process, I referred to the learning methods and processes of Brother Bird, Brother Ma, the old boy and other parties! Device or software for variable language conversion in shellshell programming: compiler, interpreter programming language: machine language, assembly language, high-level language: static language: compiled language has a development environment and does not need additional binary programs. Convert it directly to binary through the compiler and then execute it independently: strongly typed (variable) converted to executable format language type: C, C++, JAVA, C # dynamic language: interpretive language feature: weak type while interpreting language type: PHP, SHELL, Python, perl programming model process-oriented: SEHLL,C programming focus on the problem-solving process itself suitable for the development of small object-oriented: JAVA Python abstracts the project to be implemented into objects, defining the actions between objects suitable for the development of large application variables: memory space, named memory space memory: addressed storage unit variable type (defining the format and length of stored data): character value integer floating point time Boolean (logical, true and false) logical operation: and, or, XOR and operation: both are true As long as one false is false or operation: as long as one is true, the result is true non-operation: take anti-XOR operation: Operand opposite is true, the same is false strongly typed variable: variable must be declared beforehand, even initialize before use: numeric initialization defaults to 0, character default initialization to null (NULL) weakly typed variables: variables are declared when they are used, do not distinguish between types Default is string variable assignment: VAR_NAME=VALUE description: variable name (VAR_NAME) = value (VALUE) bash variable type: environment variable: local variable: (local variable) location variable: special variable: local variable: VARNAME (variable name) = VALUE (value) scope entire bash process local variable local VARNAME (variable name) = VALUE (value) scope current code segment environment variable: scope is the current shell Process and its child processes export VARNAME (variable name) = VALUE (value) export means "export" That is, in order to export an environment variable script, it will start a child shell process on the command line, and the script started on the command line will inherit the script automatically executed by the current shell environment variable system (non-command line startup), so you need to self-define each environment variable location variable: $n th location variable special variable: $? Example of the return value of the execution status of the last command: echo $? Program execution, two types of return value Program execution result Program status return Code: correct execution 1-255: error execution undo variable unset VARNAME (variable name) View current shell variable set View current shell environment variable printenvenvexport script: stacking of commands, according to actual needs, combined with command flow control mechanism to achieve the source program first script cat fisrt.sh #! / bin/bash# comment line Do not execute cat / etc/fstabla / var save exit chmod + x fisrt.sh/dev/null software device, bit bucket data black hole reference variable: ${VARNAME}, parentheses can omit single quotation marks, strong references, do not make variable replacement double quotes: weak references, internal variables do replace variable names rule letters, numbers, underscores You can't start with a number, you can't repeat the name with the existing variable name in the system, exercise 1: write a script 1, condition 5 users, user1....user52, the password of each user is the same as the user name, and it is required that the execution result information of the passwd command will not be displayed after adding the password. 3, after each user has been added, the execution result information of the command will not be displayed. Show user so-and-so has finished adding #! / bin/bash# description: enter the user name to be created on the keyboard, and automatically generate the same password as the user name during execution, but do not display the passwd execution process information # description: after the addition is completed, it shows that the user has finished adding the # read command to read the keyboard input # verify whether the password has been created successfully Use su-read-p "input a user:" valuseradd $valecho "$val" | passwd-- stdin $val & > / dev/nullecho "Add $val requests fulfilled ~" id $val exercise 2: write a script 1, use a variable to save a user name 2, delete the user in this variable And delete its home directory 3. Display the "user deletion completed" message #! / bin/bash#echo to see which users are: 'cat / etc/passwd | cut-F1-dviso' "echo-e" to see which users:\ n $(cat / etc/passwd | cut-F1-d:) "read-p" Delete a user: "valuserdel-r $valecho" Del $val fulfilling conditions to determine whether shell-n checks shell syntax error shell-x checks shell compliance Line process implementation condition judgment condition test type integer test: equal to not equal to character test: is it a file test: whether there is a conditional test expression (expression refers to an expression) [expression] there must be spaces at both ends of parentheses [[expression]] test expression integer comparison (integer test)-eq tests whether two integers are equal For example, $A-eq $B-ne tests whether even integers are unequal, unequal to true, equal to false-gt tests whether one number is greater than another: greater than true, otherwise false-lt tests whether a number is less than another: less than true, otherwise false-ge is greater than or equal to-le is less than or equal to the logical relationship between commands and: & when the first condition is true, the second condition does not need to be judged. When the first condition of the final result is true, the second condition must judge the example:! Id user6 & & useradd user6 description: if! If id user6 is true, execute useradd user6 if! If id user6 is false, useradd user6 is not executed. Example:! Id user6 & & useradd user6 description: do not create if the user exists, create logic if the user does not exist or: | example: id user6 | | useradd user6 description: no creation if the user exists, creation condition judgment if the user does not exist, control structure but branch if statement if judgment condition; thenstatement1 (statement 1) statement2 (statement 2)... fi double branch if statement if judgment condition Thenstatement1 (statement 1) statement2 (statement 2)... elsestatement3 (statement 3) statement4 (statement 4)... fiexit n means exit (n) example: determine whether the user exists, if not, create the user and password, and prompt that the creation is successful! #! / bin/bash#read-p "please input:" NAMEif id $NAME & > / dev/null;then echo "$NAME user already exists" else useradd $NAME echo $NAME | passwd-- stdin $NAME & > / dev/null echo "user $NAME added successfully." Fi example: if the number of lines in the / etc/passwd file is greater than 100, the file #! / bin/bashLINES= `wc-l / etc/ passwd`FINLINES = `echo $LINES | cut-d'-f1` [$FINLINES-gt 50] & & echo "/ etc/passwd is a big file." | | echo "/ etc/passwd is a small file." Example: if the user exists, it shows that the user already exists, otherwise, add the user id user1 & & echo "user1 exists" | | useradd user1 example: if the user does not exist, add it; otherwise, show that the user already exists! Id user1 & & useradd user1 | | echo "user1 exists." Example: if the user does not exist, add and give the password; otherwise, it already exists! Id user1 & & useradd user1 & & echo "user1" | passwd-- stdin user1 | | echo "user1 exists" exercise: write a script and add 3 users user1,user2,user3. But it is necessary to judge whether the user exists first, and then add 2. After the addition is completed, it shows that a total of several users have been added. Of course, it cannot include the number of users that have not been added because of the pre-existence. Finally, it shows how many users #! / bin/bash# create users on the current system! Id user1 & > / dev/null & & useradd user1 & & echo "user1" | passwd-- stdin user1 & > / dev/null | | echo "user1 exists"! Id user2 & > / dev/null & & useradd user2 & & echo "user2" | passwd-- stdin user2 & > / dev/null | | echo "user2 exists"! Id user3 & > / dev/null & & useradd user3 & & echo "user3" | passwd-- stdin user3 & > / dev/null | | echo "user3 exists" # shows the number of current users USERS= `wc-l / etc/passwd | cut-d:-F1 `echo "$USERS users." Exercise: add a user and determine whether it exists. If it exists, it will show "already exists". If it does not exist, create a password with the same name as the user, and display "Add $val satisfied input a user ~" #! / bin/bashread-p "input a user:" val! Id $val & & useradd $val & & echo "$val" | passwd-- stdin $val & & echo "Add $val already exists" exercise | echo "$val already exists" exercise: write a script, given a user 1, if its UID is 0, display this as administrator 2, otherwise, show it as the first method for ordinary users #! / bin/bashread-p "enter the user name:" NAMEUSERID= `id-u $name `if! Id $NAME & > / dev/null; thenecho "." else if [$USERID-eq 0]; thenecho "." echo "$NAME is the administrator." Elseecho "." echo "$NAME is the ordinary user" fi echo "." the second method of fi: #! / bin/bash# needs to improve read-p "Please enter the user name:" NAME#NAME=fanUSERID= `id-u $NAME`! Id $NAME & & echo "user does not exist!" | | [$USERID-eq 0] & & echo "admin" | | echo "Common user." Exercise: determine whether there are users in the current system whose default shell is bash, and if so, show how many such users are. Otherwise, it will show that there are no such users #! / bin/bash#grep "\" / etc/passwd | cut-d:-f3`GroupID = `GREP "^ $ID\ >" / etc/passwd | cut-d:-f4`if [$UserID-eq $GroupID] Thenecho "goodwill ~ (UID is the same as GID)" elseecho "badger ~ (UID is different from GID)" fishell conditional judgment and arithmetic operation 1, let arithmetic expression let C=$A+$B2, $[arithmetic expression] C $[$arithmetic B] 3, $((arithmetic expression)) C $(($arithmetic B)) 4, exprC= `Expr $password $B` exercise: given a user, get its password warning period Then determine whether the last modification time of the user is less than the warning period, then "warning" is displayed. Otherwise, the method of "find" is displayed: #! / bin/bashread-p "Please enter the user:" IDTIMESTAMP= `date +% s`TODAY = `let today=$TIMESTAMP/ 86400`UserID = `grep "^ $ID\ >" / etc/passwd | cut-d:-f3`ti2 = `let Ti1=$TODAY-$ user ID `ti3 = `grep "^ $ID\ >" / etc/passwd | cut-d:-f6`if [$ti2 "
< $ti3 ];thenecho " warning!!! "elseecho "find!!! "fi二方法:#!/bin/bashread -p "请输入用户:" IDW=`grep "^$ID\> < FILENAME说明:whlie 循环读取FILENAME中的每一行,放在变量LINE中,然后再循环中处理LINE中的行示例:(待完善)判断/etc/passwd中的那个用户的shell是bash,如果是bash就显示用户名,否则不显示名字#!/bin/bash#FILE=/etc/passwdlet I=0while read LINE;do [ `echo $LINE | awk -F : '{prinf $3}'` -le 505 ] && continue #用户ID大于505就不在判断,提前进入下一循环 [ `echo $LINE | awk -F : '{prinf $7}'` == '/bin/bash' ] && echo $LINE | awk -F : '{print $1}' && let I++ [ $I -eq 6 ] && break #只读取前6个用户done < $FILEcontinue示例:计算100以内所有偶数和#!/bin/bash#let SUM=0let I=0while [ $I -lt 100 ];do let I++ if [ $[$I%2] -eq 0 ];thencontinue fi let SUM+=$Idoneecho $SUM break示例:从1加到1000,知道和为5000就退出循环不再相加#!/bin/bash#declare -i SUM=0for I in {1..1000};do let SUM+=$I if [ $SUM -gt 5000 ];thenbreak fidoneecho "I=$I"echo "SUM=$SUM"break示例:判断一个文件是否存在,用户输入quit就退出#!/bin/bash#while :;do read -p "input filename:"FILENAME [ $FILENAME=='quit' ] && break if [ -e $FILENAME ];then echo "$FILENAME exists." else echo "No $FILENAME" fidoneecho "Quit." 写一个脚本:说明:此脚本能于同一个repo文件中创建多个yum源的指向1、接受一个文件名作为参数,此文件存放至/etc/yum.repos.d目录中,且文件名以.repo为后缀,要求此文件不能事先存,否则,报错2、在脚本中,提醒用户输出repo id ,如果为quit,则退出脚本,否则,继续完成下面的步骤3、repo name以及baseurl的路径,而后以repo文件的格式将其保存到指定的文件中4、enabled默认为1,而gpgcheck默认为05、此脚本会循环多次,除非用户为repo id指定为quit#!/bin/bash#REPOFILE=/etc/yum.repos.d/$1if [ -e $REPODILE ];then echo "$1 exists." exit 3firead -p "input ID:" REPOIDuntil [ $REPOID == 'quit' ];do echo "[$REPOID]" >> $REPOFILE read-p "input name:" REPONAME echo "name=$REPONAME" > > $REPOFILE read-p "input Baseurl:" REPOURL echo-e 'enabled-1\ ngpgcheck=0' > > $REPOFILE read-p "input ID:" REPOIDdone example: calculate the sum of all positive integers up to #! / bin/bash#declare-I I=1declare-I SUM=0while [$I-le 100] Do let SUM+=$I let I++doneecho "$SUM" example: when a user enters a string, it is converted to uppercase, and enter 'quit' to exit #! / bin/bash#read-p "input something:" STRINGwhile [$STRING! =' quit'] Do echo $STRING | tr 'amurz' Amurz' AmurZ' read-p "input something:" STRINGdone example: exercise: check whether hadoop has logged in every 5 seconds. If logged in, it shows that it has logged in. Exit prompt: sleepsleep 3 delay 3 seconds #! / bin/bash#who | grep "hadoop" & > / dev/nullRETVAL=$?while [$RETVAL-ne 0]; do echo "`date`, hadoop not is log!" Sleep 5 who | grep "hadoop" & > / dev/null RETVAL=$?doneecho "`date`hadoop is logged!" Example: 1. Display a menu to the user d | D) show disk usagesm | M) show menory usagess | S) show swap usages*) quit2. Display the content of the response when the user has given the option #! / bin/bashcat / dev/null;thenecho "192.168.0.Secreti online" elseecho "192.168.0.Secreti not online" fidonewhile loop #! / bin/bash#declare-I I=151while [$I-le 254]; do let I + if ping-c 1-W 1 192.168.3.Secreti & > / dev/null Thenecho "192.168.3.if ping I online" elseecho "192.168.3.These I are not online" fidoneuntil cycle #! / bin/bash#declare-I I=191until [$I-gt 254]; do let I + if ping-c 1-W 1 192.168.3.roomI & > / dev/null Thenecho "192.168.3.The online" elseecho "192.168.3.offline" fidoneshell programming: function and function function code reuse, structured programming, can not be run independently, need to be executed when called Can be called multiple times to define function method 1 function FUNCNAME {command} define function method 2 FUNCNAME () {command} Custom execution status return value return # #: function FUNCNAM N1 N2 $1 N1 $2 N2 example: multiple display menu #! / bin/bash#function SHOWM {# define function SHOWMcat / dev/null Thenuseradd $USERNAMEecho $USERNAME | passwd-- stdin $USERNAME & > / dev/nullreturn 0elsereturn 1fi} ADDUSERecho $? if [$?-eq 0]; thenecho "add user finished." elseecho "Failuer." fi extension: add multiple users #! / bin/bash#ADDUSER () {USERNAME=$1if! Id-u $USERNAME & > / dev/null;thenuseradd $USERNAMEecho $USERNAME | passwd-- stdin $USERNAME & > / dev/nullreturn 0elsereturn 1fi} for I in {1.. 10}; doADDUSER user$Iif [$?-eq 0] Thenecho "add user$I finished." elseecho "add user$I Failuer." the fidone function accepts a parameter example #! / bin/bash#TWOSUM () {echo $[$1room2]} TWOSUM 56SUM = `TWOSUM 56` # saves the execution result of the function to a variable. You can do further echo $SUM example: add two adjacent numbers within 10: add #! / bin/bash#TWOSUM () {echo $[$1roomroom2]} for I in {1.. 10} Dolet Junction $[$Ihum1] TWOSUM $I $Jecho "$I + $J = `IJ`" done example: write a script to determine which hosts are online between 192.168.0.200-192.168.0.254. Requirements: 1. Use the function to implement the decision process of a host. 2. Call this function in the main program to determine the online condition of all hosts within the specified range. The first method: #! / bin/bash#PING () {if ping-c 1-W 1 $1 & > / dev/null;thenecho "$1 online" elseecho "$1" fi} for I in {200. 254} Do PING 192.168.0.$Idone#for I in {200... 254}; another network segment of do#ping # PING 192.168.2.$I#done second method: #! / bin/bash#PING () {if ping-c 1-W 1 $1 & > / dev/null;thenreturn 0 elsereturn 1 fi} for I in {200... 254} Do PING 192.168.0. I if [$?-eq 0] Thenecho "192.168.0.SecretI online" elseecho "192.168.0.SecretI not online" fidone writes a script 1, and the function accepts a parameter as the user name to determine whether a user exists. If it exists, it returns the user's shell and UID, and returns the normal state value. If it does not exist, the user does not exist, and returns the error status value 2. Call the function extension 1 in the main program: in the main program After letting the user enter the user name, pass it to the function to judge extension 2: enter the user name in the main program and do not exit the script, but prompt the user to continue to enter the next user name, but exit #! / bin/bash#ADDUSER () {USERNAME=$1if id-u $USERNAME & > / dev/null if the user enters Q or Q Thenreturn 0elsereturn 1fi} read-p "input:" Uecho "= =" until [$U = = Q-o $U = = Q]; doADDUSER $Uif [$? = = 0] Then# echo "$U exists" sh= `grep "^ $U" / etc/passwd | awk-F:'{print $7} '`ui= `grep "^ $U" / etc/passwd | awk-F:' {print $4} '`echo "$U shell = $sh, UID = $ui" echo "=" read-p "input again:" U echo "=" else echo "$U does not exist" echo "=" read-p "input again:" U echo "=" fidoneecho "quit..." echo "="
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.