Technology Sharing

[Linux][Shell][Shell variables] Detailed explanation

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina


1. Local variables

  • Define Shell variables. The variable name does not need to be prefixed with$
  • Local variablesOnly valid during the user's current shell lifetime

2. Variable definition

  • Variable name requirements: composed of letters, numbers, and underscores. It can start with a letter or an underscore.
  • Variable names are strictly case-sensitive

3. Get the variable value

  • apostrophe: What you see is what you get, strong reference
  • Double quotes: Output all contents in quotation marks, identify special symbols, weak quotes
  • No quotes: Continuous symbols can be enclosed without quotation marks. Spaces will cause ambiguity. It is best to use double quotation marks.
  • Backtick: Quote the command execution result, equal to$()Usage

4. Special variables

  • Special shell variables, used in scripts, functions, etc. to pass parameters

  • There are special, positional parameter variables as follows

    variableeffect
    $0Get the shell script file name and script path
    $nGet the nth parameter of the shell script, n is between 1 and 9, if it is greater than 9, some{},like{$10}
    $#Get the total number of parameters after the executed shell script
    $*Get all the parameters of the shell script. Without quotes, it is equivalent to$@The effect of adding quotation marks "$*" isReceives all parameters as a single string
    $@Without quotation marks, the effect is the same as above. With quotation marks,Receives all parameters as separate strings

5. Special state variables

  • Search methodman bash,searchSpecial Parameters

    variableeffect
    $?The return value of the last command execution status, 0 for success, non-0 for failure
    $$The process number of the current shell script
    $!PID of the last background process
    $_Get the last parameter of the last command

6. Shell built-in variable commands

1.echo

  • parameter
    • -n: Output content without line break
    • -e: Interpret escape characters
      • n: Line break
      • r: Enter
      • t:tab
      • b:backspace
      • v: vertical tab character

2.eval

  • Function: Execute multiple commands
  • Exampleeval ls; cd ~

3.exec

  • Function: Do not create a child process and execute subsequent commands.execAfter execution, automaticallyexit

7. Intercepting strings

  • grammar

    grammareffect
    #Remove the shortest match from the beginning
    ##Remove the longest match from the beginning
    %Remove the shortest match from the end
    %%Remove the longest match from the end
    #Specify character content interception
    a*cMatches a string that starts with a, has any characters in the middle, and ends with c
    ${变量}Returning the value of a variable
    ${#变量}Returns variable length, character length
    ${变量:start}Returns the character after the value of the variable offset
    ${变量:start:length}Extract the length-limited characters after offset
    ${变量#word}Delete the shortest matching word substring from the beginning of the variable
    ${变量##word}Delete the longest matching word from the beginning of the variable
    ${变量%word}Delete the shortest matching word substring from the end of the variable
    ${变量%%word}Delete the longest matching word substring from the end of the variable
    ${变量/pattern/string}Replace the first match of pattern with string
    ${变量//pattern/string}Replace all patterns with string
  • Operation Example: Delete the file name

    # 通过⼦串的替换⽅式
    snowk@SnowKYP# f=stu_102999_1_finished.jpg
    
    # 变量的⼦串功能,去掉后缀
    snowk@SnowKYP# echo ${f//_finished/}
    stu_102999_1.jpg
    
    # 利⽤变量的反引⽤替换⽂件名
    snowk@SnowKYP# mv $f `echo ${f//_finished/}`
    
    # 剩下的⽂件,利⽤循环操作
    # 找出剩下所有需要替换的jpg⽂件
    snowk@SnowKYP# ls *fin*.jpg
    stu_102999_2_finished.jpg stu_102999_3_finished.jpg stu_102999_4_finished.jpg
    stu_102999_5_finished.jpg
    
    # 写shell循环代码,循环操作
    # 去掉所有jpg⽂件的_finished后缀
    snowk@SnowKYP# for file in `ls *fin*.jpg`;do mv $file `echo ${file//_finished/}`;done
    
    snowk@SnowKYP# ls *.jpg
    stu_102999_1.jpg stu_102999_2.jpg stu_102999_3.jpg stu_102999_4.jpg stu_102999_5.jpg
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

8. Special shell expansion variable processing

1. Grammar

  • Function: These four extended variables are all used to judge and process the values ​​of variables
  • grammarparameter,参数,范围
    • ${parameter:-word}:ifparameterThe variable value is empty, returnwordString
    • ${parameter:=word}:ifparameterIf the variable value is empty,wordSubstitutes a variable value and returns its value
    • ${parameter:?word}:ifparameterThe variable value is empty.wordAsstderrOutput, otherwise output variable value
      • Used to set the error message returned when the variable is empty and an error occurs
    • ${parameter:+word}:ifparameterIf the variable value is empty, do nothing.wordreturn

2. Application scenarios

  • Data backup, script to delete expired data
    # 原脚本命令,有bug,有歧义
    find ${file_path} -name '*.tar.gz' -type f -mtime +7 | xargs rm -f
    
    # 修正后的脚本命令
    # 如果有bug起义,就在当前目录搜索并执行删除
    find ${file_path:=/tmp} -name '*.tar.gz' -type f -mtime +7 | xargs rm -f
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6