Shell is a program written in C language, which is a bridge for users to use Linux. Shell is both a command language and a programming language.

A Shell is an application that provides an interface through which the user accesses the services of the operating system kernel.

Ken Thompson’s SH was the first Unix Shell, and Windows Explorer was a typical graphical Shell.


A Shell script

A Shell script is a script program written for the Shell.

The industry generally refers to shell scripts, but readers should know that shell and shell script are two different concepts.

For the sake of brevity, the term “shell programming “used in this article refers to shell scripting, not to developing the shell itself.

#! /bin/bash

touch hello.txt
#Variable types are strings by default and cannot be directly computedEcho" The data itself is plural "> > hello. TXT echo" = = = = = = = = = = = = = = = = = = = = = = = = = special variable $n $# $* $@ = = = = = = = = = = = = = = = = = = = = = = = = = "echo" $HOME "echo "$SHELL" echo "$USER"# The $1Get the first argument,$2Get the second parameterEcho "The first wife is $1, it's a beautiful city"# $#Gets the number of input parametersEcho "This time I have $# concubine"#$* represents all parameters as a wholeEcho "* * *"# $@Represents all parameters and treats them differently
# shellcheck disable=SC2145Echo "Concubine list @: $@"#$? Execution status of the last command. 0: correctly executed. Non-0: execution error (the exact number is up to the command itself)Echo "Last command execution status: $? "Echo" = = = = = = = = = = = = = = = = = = = = = = = = = define variables (along with cancellation) = = = = = = = = = = = = = = = = = = = = = = = = = A = 1 "echo", on both sides of the equal sign cannot have Spaces "echo" variable names can be composed of letters, Numbers, and underscores, "Echo" variables are strings by default and cannot be directly computed. The value of "echo" variables must be enclosed in double or single quotation marks if there are Spaces. "Z=1 echo" $Z "echo" = = = = = = = = = = = = = = = = = = = = = = = = = operator = = = = = = = = = = = = = = = = = = = = = = = = = "echo" is one of three ways, $((operator))" echo "1. $((8 + 8 * 8))"# shellcheck disable=SC2007
echo "  2. $[8 + 8 * 8]"
# exprEcho "3. Expr 8 + 8 * 8" echo" Instead of declaring variables, expr operators have Spaces between them, The multiplication sign also escapes /*, And also can't operation two or more Numbers "echo" = = = = = = = = = = = = = = = = = = = = = = = = = if conditional = = = = = = = = = = = = = = = = = = = = = = = = = "echo" basic grammar [condition] (pay attention to the condition [] returns true if the condition is empty. [] returns true. [] returns false. "echo" can also be a conditional expression "echo". , 0, which means true, but in the sh script, whether the true and false branches are executed, Is 0 "echo" = = = = = = = = = = = = = = = = = = = = = = = = = (1) string comparison = = = = = = = = = = = = = = = = = = = = = = = = = "echo" = string comparison"# shellcheck disable=SC2034str="hello" if [ "$str" ]; Then echo "true: {$STR} not empty "else echo "false: {$string STR} is empty "fi echo" = = = = = = = = = = = = = = = = = = = = = = = = = (2) the comparison between two integer = = = = = = = = = = = = = = = = = = = "echo" - lt is less than (less than) - le less than or equal to, less Equal) "echo "-eq is equal to (equal) -ne is not equal to (equal)" echo "-gt is greater than (greater than) -ge is greater equal"# shellcheck disable=SC2050if [ 23 -ge 22 ]; then echo "true: 23 >= 22" else echo "false: 23 "22" fi echo "= = = = = = = = = = = = = = = = = = = = = = = = = (3) shall be carried out in accordance with the file permissions determine = = = = = = = = = = = = = = = = = = =" echo "- read access to r (read)" echo "- w Have write permissions (write) "echo" - x has the authority to perform (execute) "echo" = = = = = = = = = = = = = = = = = = = = = = = = = (4) according to the file type to judge the = = = = = = = = = = = = = = = = = = = "echo" - e "Echo "-f The file exists and is a regular file (file)" echo "-d the file exists and is a directory (directory)" if [-d hello.sh]; Then echo "true: hello.sh "directory" else echo "false: Hello. Sh is not a directory "fi echo" = = = = = = = = = = = = = = = = = = = = = = = = = flow control (key) = = = = = = = = = = = = = = = = = = = "echo" = = = = = = = = = = = = = = = = = = = = = = = = = (1) if judgment = = = = = = = = = = = = = = = = = = = "echo" basic syntax: if after have the Spaces and fi closed-loop "echo" if [condition]; Then "echo" true branch "echo "fi" echo "====== elif and else ======" echo" if [condition]; then commands; elif [ condition ]; then commands; The else commands; Fi "echo" = = = = = = = = = = = = = = = = = = = = = = = = = = (2) the case statement = = = = = = = = = = = = = = = = = = = = = = = ="
# shellcheck disable=SC2162
# read -p "please input a number to case statement:" num # print a message to prompt the user for input, which is assigned to the num variablenum=3 case "$num" in 1) echo "The num you input is 1" ;; [2-5]) echo "The num you input is 2-5" ;; [6-9]) echo "The num you input is 6-9" ;; *) echo "both please input the number (1-9] int" esac echo "= = = = = = = = = = = = = = = = = = = = = = = = = = (3) for loop = = = = = = = = = = = = = = = = = = = = = = = =" sum = 0 for ((i = 1; i <= 100; I ++)) do sum=$((sum + I)) done echo "1~100: sum" echo" $p" done sum2=0 k=1 while [$k -le 50] do sum2=$((sum2 + k)) k=$((k + 1))
#echo "= = = = = = = = = = = = = = = = = = = = = = = = = = (3) read read from the console input = = = = = = = = = = = = = = = = = = = = = = = ="
#read -r -p "Please enter your favorite actor, -r will normally read the backslash:" girlName
#echo "$girlNameIt's your girlfriend."
#read -r -t 3 -p "Please enter another female star in three seconds:" other
#
#if [ "$other" ]; then
#  echo "$otherAnd your girlfriend."
#else
#  echo "I knew you were single-minded."
#fiEcho "= = = = = = = = = = = = = = = = = = = = = = = = = = system function = = = = = = = = = = = = = = = = = = = = = = = =" echo "= = = = = = = = = = = = = = = = = = = = = = = = = = (1) the basename = = = = = = = = = = = = = = = = = = = = = = = ="#Basic syntax: basename NAME [SUFFIX]
#Delete the leading directory and print the name
#Suffixes can also be removed if specified
#$(CMD) specifies the output
fileNameWithSuffix=$(basename include/stdio.h)
echo "$fileNameWithSuffix"  # stdio.h
fileName=$(basename include/stdio.h .h)
echo "$fileName" # stdio

echo "========================== (2) dirname ========================"
# Usage: dirname [OPTION] NAME...
#Print the content before the last slash of Name (the directory where Name is, and delete the last slash)
#Enter if Name does not contain a slant bar'. 'Represents the current directorydir1=$(dirname /usr/bin/) dir2=$(dirname /AuI18N/2052/usr/bin/a.txt) dir3=$(dirname stdio.h) echo "dir1: $dir1" echo "dir2: $dir2" echo "dir3: $dir3 "echo" = = = = = = = = = = = = = = = = = = = = = = = = = = a custom function = = = = = = = = = = = = = = = = = = = = = = = = "echo" standard writing: "Function name() {echo "== name() ==" return 0 # [return value], value range: 0-255 #} name#The function returns a value only via $? System variables are obtained and can be displayed plus. If not, the result of the last command is returned
echo "func result : $?"

function twoSum() {
  s=0
  s=$(($1+$2))
  echo "twoSum result : $s"
}

#Shell functions may or may not be called with arguments passed to them
#If no arguments are passed, simply give the function name: name
#If you pass parameters, separate multiple parameters with Spaces: Name param1 param2 param3twoSum 6 6 echo "========================== sed ========================" echo "Usage: Sed [option] 'command' fileName" echo "-n, --quiet, --silent S replace D delete p print q exit I line before a line after "echo "-e and; Can implement multiple CMD"#sed "s/u/UC/g" abc.txt  # u ==> UC, g stands for whole line replacement
#echo "= ="
#sed "s/u/UC/" abc.txt
# sed "s/a//g" abc.txt   # Delete all the a's
# sed "s/#.*//g" abc.txt   # -i will modify the source file
# sed "s/\s*#.*//g" abc.txt   # \s* represents 0 or more Spaces
# sed "s/\s*#.*//g; /^$/d" abc.txt # /^$/d Delete blank lines
# sed "/a/q" abc.txt # Exit at first A
# sed -n "/a/p" abc.txt Print the line that matches a
# sed "3q" abc.txt Print to the third line and exit
# sed "3p" abc.txt Print on the third line
#sed "/^wo/a cao" abc.txt # a adds a line after the matching line
#sed "/^wo/i ai~" abc.txt  # I adds a line before the matching line
#cmd1="2a mei nv22"
#sed "$cmd1" abc.txt
#sed "3s/a/TT/g" abc.txt # just replaced the a in the third row with TT
#sed "/lai/d" abc.txt
#sed "4d; s/wo/ni/g" abc.txt  #; Number to implement multiple commands, delete the fourth line, and replace the character
#sed -e "4d" -e "s/wo/ni/g" abc.txt  #; Number to implement multiple commands, delete the fourth line, and replace the characterEcho "= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = awk = = = = = = = = = = = = = = = = = = = = = = = = = = = = =" echo "commonly used functions: tolower () : string to lowercase. Length () : Returns the length of the string. Substr () : Returns a substring. Rand () : random number. "Echo "awk [options parameters] 'pattern1{action1} Pattern2 {action2}... awk [options parameters] 'pattern1{action1} pattern2{action2}... '" fileName echo "pattern: indicates the data that awK looks for. "echo "action: A series of commands to execute when a match is found. "echo" -f specifies the delimiter. "echo" -v defines variables. Also can not take inside of outside "awk - F" : "' / ^ root / {print $7} 'demo. TXT awk - F" : "' / ^ root / {print $1 ". "$7} 'demo. TXT awk - F" : "' / ^ root / {printf (" % s is the first column content, 7 column content is: % s! \n", $1, $7)}' demo.txt#The BEGIN and ENDAwk -f ":" 'BEGIN{print "=== lu Ben wei niu bi~ ==="} /^root/ {printf(" %s, %s! \n", $1, $7)} END{print "=== bi xv di ! = = = "} 'demo. TXT awk - F ":"' the BEGIN {print "= = = lu Ben wei niu bi ~ = = ="} {printf (" % s is the first column content, 7 column content is: % s! \n", $1, $7)} END{print "=== bi xv di ! {print $3 + I}' demo. TXT awk -f ":" -v I =1 '{print $3 + I}' demo. TXT#Awk built-in variablesAwk -f ":" '{printf (" file: % s, line number: % s, the bank, a total of % s in the first column: % s \ n ", FILENAME, NR, NF, $1)}' demo. TXT#Print blank line numbersAwk '/ ^ ${printf (" empty line Numbers: % s \ n ", NR)}' demo. TXT echo "= = = = = = = = = = = = = = = = = = wc = = = = = = = = = = = = = = = = =" echo "the Usage: wc [OPTION]... [FILE]..." Echo "WC will print out the file name, Can use awk to remove "total_lines = $(wc -l demo. TXT | awk -f" "'} {print $1) total_bytes = $(wc - c demo. TXT | awk -" "' F {print $1}') echo "demo.txt "==>> > $total_lines $total_bytes" echo "================ sort ==================" echo "Usage: sort [OPTION]... [FILE]..." Echo "-n, sort by value -r, reverse order -b, ignore the leading space -t, specify the column separator character -k, "Sort -t "-" -k 3 -n sort. TXT sort -t "-" -k 3 -n -r sort.txtCopy the code

FAQ:

#! /bin/bash
#Calculate the summation of the third column in demo.txt$(awk -f ":" -v sum=0 '{sum+=$3} END{print sum}' demo.txt) echo "$third_sum" unset third_sum
#Determines whether a file existsif [ -f sort.txt ]; Then echo "sort. TXT "exists" else echo "sort. TXT "does not exist" fi
#Look for the file name that contains the character Shen in the current directory
#Uniq to heavy
#Uniq follows with the number of line repeats
grep -r shen | awk -F ":" '{print $1}' | uniq -c

#Output multiples of 7 between 0 and 500
#for ((i = 0; i <= 500; i++))
#do
#  if [ $((i % 7)) -eq 0 ]; then
#    echo "$i"
#  fi
#done
#unset "$i"
#exit 0

#for i in{0.. 500}
#do
#  if [ $((i % 7)) -eq 0 ]; then
#    echo "$i"
#  fi
#done
#unset "$i"
#exit 0

#The number ranges from 0 to 500, and the step is 7
# seq 0 7 500

#Write a bash script to count words with less than 8 letters in a text file called nowcoder.txt.
#
#
#
# sample:
#Suppose nowcoder.txt has the following content:
#how they are implemented and applied in computer
#
Your script should output:
#how
#they
#are
#and
#applied
#in
awk '{
  for (i=1; i <= NF; i++) {
      if (length($i) < 8){
          print $i
      }
  }
}' n.txt

#Prints blank lines, or lines with only Spaces and tabs
awk 'NF == 0 {print NR}' n.txt

#Count the number of occurrences of each wordecho "===!! @@=====" awk '{ for (i=1; i <= NF; i++) { print $i } }' now.txt | sort | uniq -c | awk '{printf("%s %s\n", $2, $1)}' | sort -k 2 -n > res.txt echo "=====" awk '{ for (i = 1; i <= NF; ++i) mp[$i]++; } END { for (k in mp) printf("%s %d\n", k, mp[k]); } 'now. TXT | sort - k - 1 n awk' {print $2} 'nowcoder. TXT | sort - n | uniq -c | awk' $1 > {print $0} 'echo "assuming each have the same number, And each field is separated by a space example: Job salary c++ 13 Java 14 PHP 12 your script should output (in ascending order of word frequency) :  job c++ java php salary 13 14 12 " cols=$(sed "1q" nowcoder.txt | awk '{print NF}') for ((i = 1; i <= cols; i++)); do awk -v k="$i" '{printf("%s ", $k)}' nowcoder.txt echo done echo "write a bash script to count the number of 1,2,3,4,5 digits per line in a text file nowcoder.txt And count the number of 1,2,3,4,5 digits in the entire document. Example: suppose nowcoder. TXT contains the following contents: a12b8 10CCC 2521abc 9asf Your script should output: line1 number: 2 line2 number: 1 line3 number: 4 line4 number: 0 sum is 7 " awk -F "" ' BEGIN{sum = 0} { count = 0; for (i = 0; i < NF; i++) { if ($i == 1 || $i == 2 || $i == 3 || $i == 4 || $i == 5) { count++; } } sum += count; printf("line%s number:%d\n", NR, count); } END{printf("sum is %d\n", sum)} 'nowcoder.txt echo "Write a bash script to implement a requirement that the average of the input array is the first line of the input array length n the second to the n line of the array elements, as follows: Array length is 4, array elements are 1 2 9 8 Example: 4 1 2 9 8 So average value :5.000(keep three decimal places behind the decimal point) Your script to get the above input should output :5.000 "awk 'BEGIN{sum = 0; len = 0} { if (NR == 1) { len = $1; } else { sum += $1; END{printf("%0.3f\n", sum/len)}'Copy the code