Reputation: 71
I have text file with 4 entries. When I run a shell script first time, Only first entry should be picked up . when I run 2nd time, Only 2nd entry should be picked up and like this when I run the script for 5th time again 1st entry should be picked up.
Basically it should pick up the entries in the text file one by one and when it reaches last , it again should start from the first.
I initially thought of keeping one more file , with the current running entry , so when it runs next time It will check that file and process the next line. But I cannot keep any files. this logic should be handled inside the script itself without keeping any other files.
I hope I explained my problem.. Please help me with a logic for this in unix ..
Upvotes: 0
Views: 55
Reputation: 84551
You can use trap
in a brute force call to sed
to update an index within the file on termination or exit. For example:
#!/bin/bash
declare -i current_idx=0
trap 'sed -i "s/^declare[ ]-i[ ]current_idx[=].*$/declare -i \
current_idx=$(((current_idx+1) % 4))/" $(readlink -f "$0")' SIGTERM EXIT
case "$current_idx" in
0 ) printf "picked up %d entry\n" "$current_idx";;
1 ) printf "picked up %d entry\n" "$current_idx";;
2 ) printf "picked up %d entry\n" "$current_idx";;
3 ) printf "picked up %d entry\n" "$current_idx";;
* ) printf "error: current_idx is '%d'\n" "$current_idx";;
esac
Example Use
Here is the script called 11 times showing how it cycles through 4 different entries returning to the first on the 5th call.
$ (for i in {0..10}; do bash selfmod.sh; done)
picked up 0 entry
picked up 1 entry
picked up 2 entry
picked up 3 entry
picked up 0 entry
picked up 1 entry
picked up 2 entry
picked up 3 entry
picked up 0 entry
picked up 1 entry
picked up 2 entry
Note: self-modifying a script isn't good practice. Your separate-file idea was much safer. However, for your purposes, this will work. However, I make no representation about how wise or safe this is.
Upvotes: 2