两种计算的比较

时间:2021-04-22 18:43:35

标签: linux bash ubuntu devops script

#! /bin/bash
a=1
until [ $a = 61 ]
do
    echo Value of a = $a
    a=$ expr $a + 10         #First 
    echo first Value: $a          
    a=`expr $a + 10`        #What is first and Second code's difference
    echo second Value: $a      
done   

输出

mrjintophilip@LAPTOP-1D73GN8:~$ ./nnn.sh
Value of a = 1
11
first Value: 1
second Value: 11
Value of a = 11
21
first Value: 11
second Value: 21
Value of a = 21
31
first Value: 21
second Value: 31
Value of a = 31
41
first Value: 31
second Value: 41
Value of a = 41
51
first Value: 41
second Value: 51
Value of a = 51
61
first Value: 51
second Value: 61

告诉我这个bash脚本代码的含义

1 个答案:

答案 0 :(得分:0)

a=$ expr $a + 10

执行以下步骤:

  1. 用变量$a的值替换a,所以它变成
a=$ expr 1 + 10
  1. 创建一个子shell进程。
  2. 在该子 shell 中,将环境变量 a 设置为 $
  3. 从子 shell 执行 expr 1 + 10 命令。这会在标准输出上打印 11

由于环境变量仅在子shell中设置,因此它对运行脚本的原始shell中a的值没有影响。

a=`expr $a + 10`

执行以下步骤:

  1. 用变量$a的值替换a,所以它变成
a=`expr 1 + 10`
  1. 创建一个子shell。
  2. 在子 shell 中执行 expr 1 + 10,捕获其标准输出。
  3. 在原始 shell 中,将此输出存储在变量 a 中。

所以区别在于第一个执行 expr 命令的同时临时设置环境变量,而第二个将 expr 命令的输出保存到变量中。