Created
May 1, 2025 22:48
-
-
Save christophlehmann/aa6856b84597a8bdbc28d37ce9870d41 to your computer and use it in GitHub Desktop.
grep highest semantic version from stdin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash -e | |
print_help() { | |
cat <<EOF | |
Usage: cat versions.txt | $0 [OPTIONS] | |
Options: | |
--major Output major version of the latest semver | |
--minor Output minor version of the latest semver | |
--patch Output patch version of the latest semver | |
--increase-major Increment major version (resets minor and patch to 0) | |
--increase-minor Increment minor version (resets patch to 0) | |
--increase-patch Increment patch version | |
--help Show this help message | |
Grep the highest semantic version from stdin and apply options to it. Without options its just printed. It exits | |
with 1 when no semantic version is found. | |
EOF | |
} | |
which -s egrep sort bc head | |
# Check if stdin is empty | |
if [ -t 0 ]; then | |
print_help | |
exit 1 | |
fi | |
# Read and parse latest version | |
LATEST_VERSION=$(egrep '^[0-9]+\.[0-9]+\.[0-9]+$' | sort -Vr | head -n 1) | |
# Validate the latest version | |
if ! [[ "$LATEST_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then | |
echo "No semver version in input detected." >&2 | |
exit 1 | |
fi | |
# Split version | |
IFS='.' read -r MAJOR MINOR PATCH <<< "$LATEST_VERSION" | |
# Parse arguments | |
while [[ $# -gt 0 ]]; do | |
case "$1" in | |
--major) | |
echo "$MAJOR" | |
exit 0 | |
;; | |
--minor) | |
echo "$MINOR" | |
exit 0 | |
;; | |
--patch) | |
echo "$PATCH" | |
exit 0 | |
;; | |
--increase-major) | |
((MAJOR++)) | |
MINOR=0 | |
PATCH=0 | |
;; | |
--increase-minor) | |
((MINOR++)) | |
PATCH=0 | |
;; | |
--increase-patch) | |
((PATCH++)) | |
;; | |
--help) | |
print_help | |
exit 0 | |
;; | |
*) | |
echo "Unknown option: $1" >&2 | |
print_help | |
exit 1 | |
;; | |
esac | |
shift | |
done | |
# Output final version | |
echo "$MAJOR.$MINOR.$PATCH" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment