Linux - Shell - parameter acquisition

  1. Outline
    1. parameter
  2. background
    1. Review the parameters of shell scripts get
  3. Scenes
    1. the
      1. centos7

1. Parameters: Basic

  1. Outline
    1. Quick description parameter

1. Obtain parameters

  1. Get the first argument

    1. Acquisition parameters
      1. Acquisition parameters using $ {num}
      2. $ {1} acquired first parameter
    2. Code

      #!/bin/bash
      var1=${1}
      echo ${var1}
    3. other
      1. {2} can try $, $ {3} and other subsequent parameters acquired
      2. By default, if enough arguments, echo does not complain, other commands, you need to verify

2. Get more parameters

  1. Question 1: obtaining multiple parameters
    1. A get a parameter, if the parameter more, will not be a lot of trouble
  2. solve
    1. All parameters can be obtained as
  3. plan 1: $*
    1. $*
      1. Once to get all the parameters
    2. Code

      #!/bin/bash
      var1=$*
      echo ${var1}
  4. Question 2: I went to separate parameters
    1. All parameters
      1. $ * Get to the parameters, all the parameters are ranked together
    2. need
      1. I want to get a certain parameter alone
    3. solve
      1. 1 idea: you know looking for the first of several parameters
        1. Use $ {num}
      2. 2 ideas:? What you do not know what number, but you know what kind of parameters
        1. Converted into an array
          1. Temporarily not recommended
            1. Conversion array, I will not
            2. Array after conversion, do not know if the subject of the next element, required circulating operation of the array, I will not
      3. 3 ideas: Use $ @
  5. Scenario 2: $@
    1. All parameters
      1. More use when cycling
    2. Code

      #!/bin/bash
      for word in "$@"
      do
          echo ${word}
      done

3. Get the last parameter

  1. Question: The last parameter
    1. the last one
      1. I wanted to get the last parameter
  2. solve

    #!/bin/bash
    
    # 假设参数是 1 2 3
    # 最后一个参数, ${3}
    var1=${#}
    echo $var1
    echo ${!var1}
    
    # 倒数 第二个参数, ${2}
    var2=$[${#}-1]
    echo $var2
    echo ${!var2}
  3. Question: hand slipped parameters did not increase
    1. problem
      1. Suddenly hand sliding, no additional parameters
    2. result
      1. The first paragraph of printing out the script name

4. Get the name of the script

  1. Screenplay name
    1. ${0}
      1. Print $ {0} to see
  2. problem
    1. ./<script>
      1. display ./<script>
    2. bash <script>
      1. display

Guess you like

Origin www.cnblogs.com/xy14/p/12088111.html