Next element of the loop

Asked

Viewed 34 times

0

I’m trying to implement a commit search algorithm between two tags with the command git log tag1...tag2. For this I used the command git tag that returns me the tags of a repository.

With this result, I thought of iterating on it by executing the command git

for tag in $Tags
do
    git log $tag .. $proximaTag
done

My question is: How to get the value of the next tag? In this case, how to get the value of the next item in the array?

Have some better way to implement this kind of algorithm?

  • I don’t know much about bash, but following the logic of programming, wouldn’t you be able to get the index of that iteration? then you would do something like $tags[i] .. $tags[++i]. However, you probably would have to make an auxiliary index to not modify the current value.

1 answer

2


In the case of the loop for you will not be able to catch the next element from the list but it is possible to use the loop while and the command shift to do so:

show_commits(){    
    first_tag=${1}
    while true; do
        shift
        next_tag=${1}
        if [[ $next_tag == '' ]]; then
            break
        else
            git log "${first_tag}".."${next_tag}" --pretty=%H
            echo
            first_tag=$next_tag
        fi
    done
}

show_commits $( git tag | tac )

The list of tags is generated directly by Git and the command tac serves to reverse her order) and all of it is sent to the function as the arguments $1, $2, $3 etc. But you can do something direct like "show_commits v1.2.3 v1.2.2 v1.0.0".

However, despite receiving all of them, the function will use only one argument, see that only one argument -- ${1} -- is used to assign the value to variables first_tag and next_tag.

Therein comes the shift that takes care of shifting the arguments to the left, so $1 turns $0, $2 turns $1 etc and $0 is always discarded in the process... this is done until the variable next_tag receives an empty value, which means there are no more values and the loop is broken.

  • I just found strange the description of '$1virando$0` and being discarded, but otherwise a great answer

  • In Bash the $0 parameter is the name of the function/command that was invoked, so the first run takes something like "show_commits v3.0 v2.0 v1.0" and I take $1 which is "v3.0" in the first shift the argument list turns to "v3.0 v2.0 v1.0", when I read $1 again and pick up "v2.0" and so on until the reading returns a string empty.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.