Self-updating shell script

question

The contents of shell file 1.sh are as follows:

num=1
let num++
echo $num

How to make num use the last calculated value in the next run?

plan

Instead of using external file storage here, try updating the script itself with a redirect.
Since you want to modify yourself, you must first get your own path.

  1. get script path
path="$(dirname "$0")"
  1. Modify the content
awk -v num=$num  '/^num=[0-9]/{gsub("[0-9]+",num)} {print}' 1.sh
  • -v num=$num pass the shell variable value into awk to use
  • /^num=[0-9]/ match variable definition line
  • gsub("[0-9]+",num) Substitute variable assignment
  1. Save
    Failed method: awk '...' 1.sh > 1.sh, the file will be emptied!
    The successful practice of cups : awk '...{print >1.sh}' 1.sh
    So, what can be solved in awk, never take it outside, ☺

code

#!/bin/sh
num=1
let num++
cd "$(dirname "$0")"
awk '/^num=[0-9]/{gsub("[0-9]+",num)} {print >self}' num=$num self="$0" "$0"

Of course, you can also use sed -i. Here, use comments to locate the position to be modified.

number=5 #SAVE_NUMBER
let number++
sed -i "0,/.*#SAVE_NUMBER/s/.*#SAVE_NUMBER/number=$number #SAVE_NUMBER/" $0 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325017647&siteId=291194637