每个循环中shell脚本中的增量编号

时间:2012-06-12 15:11:08

标签: bash shell

#!/bin/bash

echo SCRIPT: $0
echo "Enter Customer Order Ref (e.g. 100018)"
read P_CUST_ORDER_REF
echo "Enter DU Id (e.g. 100018)"
read P_DU_ID

P_ORDER_ID=${P_CUST_ORDER_REF}${P_DU_ID}


#Loop through all XML files in the current directory
for f in *.xml
do
  #Increment P_CUST_ORDER_REF here
done

在for循环中,每次循环时如何将P_CUST_ORDER_REF递增1

so it READs 10000028 uses it on first loop
2nd 10000029
3rd 10000030
4th 10000031

3 个答案:

答案 0 :(得分:7)

((P_CUST_ORDER_REF+=1))

let P_CUST_ORDER_REF+=1

答案 1 :(得分:6)

P_CUST_ORDER_REF=$((P_CUST_ORDER_REF+1))

答案 2 :(得分:2)

您可以使用后增量运算符:

(( P_CUST_ORDER_REF++ ))

我建议:

  • 习惯使用小写或混合大小写变量名来避免与shell或环境变量发生潜在的名称冲突
  • 在扩展时引用所有变量
  • 通常使用带有read的-r来防止反斜杠被解释为转义
  • 验证用户输入

例如:

#!/bin/bash
is_pos_int () {
    [[ $1 =~ ^([1-9][0-9]*|0)$ ]]
}

echo "SCRIPT: $0"

read -rp 'Enter Customer Order Ref (e.g. 100018)' p_cust_order_ref
is_pos_int "$p_cust_order_ref"

read -rp 'Enter DU Id (e.g. 100018)' p_du_id
is_pos_int "$p_dui_id"

p_order_id=${p_cust_order_ref}${p_du_id}

#Loop through all XML files in the current directory
for f in *.xml
do
    (( p_cust_order_ref++ ))
done