bash 每个循环的 shell 脚本中的增量数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10999541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:28:46  来源:igfitidea点击:

Incremental number in shell script on each loop

bashshell

提问by ahmet

#!/bin/bash

echo SCRIPT: 
so it READs 10000028 uses it on first loop
2nd 10000029
3rd 10000030
4th 10000031
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

Inside the for loop how can i increment P_CUST_ORDER_REF by 1 every time it loops

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

((P_CUST_ORDER_REF+=1))

回答by Prince John Wesley

let P_CUST_ORDER_REF+=1

or

或者

P_CUST_ORDER_REF=$((P_CUST_ORDER_REF+1))

回答by mouviciel

(( P_CUST_ORDER_REF++ ))

回答by Paused until further notice.

You can use the post-increment operator:

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

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

echo "SCRIPT: ##代码##"

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

I recommend:

我建议:

  • habitually using lowercase or mixed case variable names to avoid potential name collision with shell or environment variables
  • quoting all variables when they are expanded
  • usually using -rwith read to prevent backslashes from being interpreted as escapes
  • validating user input
  • 习惯性地使用小写或大小写混合的变量名,以避免与 shell 或环境变量的潜在名称冲突
  • 展开时引用所有变量
  • 通常使用-rwith read 来防止反斜杠被解释为转义
  • 验证用户输入

For example:

例如:

##代码##