Incremental number in shell script for each loop

#!/bin/bash echo SCRIPT: $0 echo "Enter Customer Order Ref (eg 100018)" read P_CUST_ORDER_REF echo "Enter DU Id (eg 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

 so it READs 10000028 uses it on first loop 2nd 10000029 3rd 10000030 4th 10000031 
+4
source share
3 answers
 ((P_CUST_ORDER_REF+=1)) 

or

 let P_CUST_ORDER_REF+=1 
+7
source
 P_CUST_ORDER_REF=$((P_CUST_ORDER_REF+1)) 
+6
source

You can use the post-increment operator:

 (( P_CUST_ORDER_REF++ )) 

I recommend:

  • usually using lowercase or mixed case variable names to avoid potential collision of names with shell or environment variables.
  • quoting all variables as they expand
  • commonly used -r with reading to prevent backslash as an interpretation
  • user input validation

For instance:

 #!/bin/bash is_pos_int () { [[ $1 =~ ^([1-9][0-9]*|0)$ ]] } echo "SCRIPT: $0" read -rp 'Enter Customer Order Ref (eg 100018)' p_cust_order_ref is_pos_int "$p_cust_order_ref" read -rp 'Enter DU Id (eg 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 
+2
source

All Articles