What is Shell? Get started quickly with Shell!

Shell is a command line interpreter that accepts application/user commands and then calls the operating system kernel. It is a powerful programming language, easy to write, easy to debug, and highly flexible.
Insert picture description here
There are six shell parsers provided by Linux:cat /etc/shells

  • /bin/sh
  • /bin/bash, The default parser in CentOS is bash
  • /sbin/nologin
  • /bin/dash
  • /bin/tcsh
  • /bin/csh

Script format

  • Script #!/bin/bashstarts with

    #!/bin/bash
    
    echo "hello world"
    
  • Run the script file sh xx.shby: bash xx.sh, ,./xx.sh(注意需要.sh具备执行权限[x],chmod 777)

  • By touch xx.shcreating script files, by vim xx.shediting script files.

System variable

  • $HOME, The home directory of the currently logged in user
  • $PWD, The current directory path
  • $SHELL, The default shell parser
  • $USER, The currently logged-in user

Custom variable

  • Basic grammar
    • Define variable: variable = value
    • Undo variable:unset 变量名
    • Declare static variables:, readonly 变量名note that static variables cannot be undone, and restart is invalid.
    • Variable definition rules: composed of letters, numbers, and underscores, and cannot start with a number. It is recommended that environment variables be capitalized.
    • No spaces around the equal sign, strict requirements
    • Variables are of string type by default , and numerical operations cannot be performed directly.
    • If the value of the space variable, need quotes quotes
    • Promote the local variables in the script to global variables:export 变量名

Special variable

  • $n

    • Function description: n is a number. $0, On behalf of the script name;, $1-$9on behalf of the first to ninth parameters; parameters above the tenth need to be ${10}expressed.

      touch partmeter.sh

      vim partmeter.sh

      #!/bin/bash
      
      echo "$0 $1 $2"
      

      bash partmeter.sh p1 p2

      partmeter.sh p1 p2

  • $#

    • Function description: Get the number of all input parameters, often used in loops

      #!/bin/bash
      
      echo "$#"
      

      bash partmeter.sh p1 p2

      2

  • $*

    • Function description: Get all the parameters in the command line, and treat all the inputs as a whole

      #!/bin/bash
          
      echo "$*"
      

      bash partmeter.sh p1 p2
      p1 p2

  • $@

    • Function description: Get all the parameters in the command line and treat all input parameters differently

      #!/bin/bash
      
      echo "$@"
      

      bash partmeter.sh p1 p2
      p1 p2

  • $?

    • Function description: The return status of the last executed command. If the value of the variable is 0, it proves that the last command was executed correctly; if the value of the variable is non-zero, it proves that there was an error in the execution of the previous command.

Operator

  • Basic grammar
    • $((运算式))or$[运算式]
    • exprOperation ( There must be spaces between operators )
      • +,plus
      • -,Less
      • \*, Multiply
      • /,except
      • %, Take the remainder
      • Operation execution symbol: `expr 2 + 3

Conditional judgment

  • Basic grammar
    • [ condition ], Note that there must be spaces before and after the expression
    • [ test ], If the condition is not empty, it is true; [], if the condition is empty, it is false;
  • Commonly used judgment conditions
    • = String comparison
    • -lt, Less than
    • -le, Less than or equal to
    • -eq,equal
    • gt,more than the
    • ge,greater or equal to
    • ne,not equal to
    • -r, Has read permission
    • -w, Have write permission
    • -x, Have permission to execute
    • -f, The file exists and is a regular file file
    • -e, The file exists
    • -d, The file exists and is a directory
  • Multi-condition judgment
    • &&, The next command will be executed only when the previous command is executed successfully
    • ||, The next command will be executed when the previous command fails

Process control

if
  • Basic syntax: ifthere []must be a space after it, and there must be a space before and after the conditional expression elif;, stands for else if; at the fiend.

    #!/bin/bash
    
    if [ condition1 ];then
        content1
    elif [ condition2 ]
    then
        content2
    fi
    
case
  • Basic syntax: case $变量名 in value)format, ;;end of case, similar to break; *)represents the default branch; esacend;

    #!/bin/bash
    
    case $1 in
    1)
    	content1
    	;;
    2)
    	content2
    	;;
    3)
    	content3
    	;;
    *)
    	content4
    	;;
    esac
    
for
  • Basic grammar 1: for((初始值;循环控制条件;变量变化))format; domethod body; doneend; specific accumulation of 1-100 sum:

    #!/bin/bash
    
    s=0
    for((i=1;i<=100;i++))
    do
    	s=$[$s+$i]
    done
    
    echo $s
    
  • Basic syntax 2: for 变量 in value1 value2 value3Format; $@each input parameter is processed separately, and $*the input parameter is processed as a whole

    #!/bin.bash
    
    for i in "$*"
    do
    	echo "ceshi * $*"
    done
    
    for j in "$@"
    do 
    	echo "ceshi @ $@"
    done
    

    bash ceshi.sh zs ls

    The output result is:

    ceshi * zs ls

    ceshi @ zs

    ceshi @ ls

while
  • Basic grammar: while [ condition ]format; domethod body; doneend; the sum of concrete accumulation 1-100:

    #!/bin/bash
    
    s=0
    i=0
    while [ $i -le 100]
    do
    	s=$[$s+$i]
    	i=$[$i+1]
    done
    

Read to read console input

  • Basic syntax:read(选项)(参数)

    • Options
      • -p, Specify the prompt when reading the value
      • -t, Specify the time to wait when reading the value (seconds)
    • parameter
      • Variable: Specify the name of the variable to read the value
  • Example: Enter name on the console within seven seconds

    #!/bin/bash
    
    read -t 7 -p "input your name in 7 seconds" name
    
    echo $name
    

function

System function
  • basename [string/pathname][suffix], Intercept the file name under the specified path
  • dirname 文件绝对路径, Extract the path of the file from the given file name containing the absolute path
Custom function
  • Basic grammar

    // 声明函数
    function funname[()]{
          
          
    	action;
    	[return int;]
    }
    funname // 执行函数
    

Shell tool

cut command
  • Cut bytes, characters, and fields from each line of the file, and output these bytes, characters, and fields.

  • Basic usage

    • cut [选项参数] filename

    • Option parameter

      • -f, Column number, which column to extract
      • -d, Separator, split the column according to the specified separator, the default separator is a tab\t
    • Example: Use space as the separator to cut the second column of the file content and output the following content

      cut -d " " -f 2- cut.txt

and
  • Stream editor, processing one line of content at a time. When processing line content, store the current line content in a temporary buffer area called "mode space", then use the sed command to process the content in the buffer, and output the content after the processing is completed. Then process the next line until the end of the text.

  • Basic usage

    • sed [选项参数] "命令功能" filename

    • Option parameter

      • -e, Directly edit the action of sed on the specified column mode
    • Command function (commonly used)

      • a, Add
      • d,delete
      • s, Find and replace
    • For example:

      • Add content in the second line of the file: add content

        sed "2a add contend" filename

      • Delete the line containing wo in the file

        sed "/wo/d" filename

      • Replace wo in the file with ni

        sed "s/wo/ni/g" filename, gWhich stands for global replacement

      • Delete the second line of the file and replace wo in the file with ni

        sed -e "2d" -e "s/wo/ni/g" filename

awk
  • The text analysis tool reads the file line by line. By default, each line is sliced ​​with a space as a separator, and the cut part can be analyzed and processed.

  • Basic usage: awk [选项参数] 'pattern1{action1} pattern2{action2} ...' filename; pattern; match the regular expression actioncommand matching contents in line with the execution.

    • Option parameter

      • -F, Specify the input file separator
      • -v, Copy a user-defined variable
    • Built-in variables

      • FILENAME,file name
      • NR, The number of records read
      • NF, The number of domains in the browse record (after cutting, the number of columns)
    • Example: Search for all lines in the file starting with root, and output the seventh column of the line

      awk -F : '/^root/{print $7}' filename

sort
  • Files are sorted and output according to the standard output of the sorted results

  • Basic usage

    • sort(选项)(参数)

      • Options

      • -n, Sorted by numerical value

      • -r, Sort in reverse order

      • -t, Set the separator character used for sorting

      • -k, Specify the column to be sorted

      • parameter

        • Specify the list of files to be sorted
      • Example: The files are divided by colons, and the third column is sorted in reverse order

        sort -t : -nrk 3 filename

Guess you like

Origin blog.csdn.net/Nerver_77/article/details/106987280