Basically i need to create a function where an argument is passed, and i need to update the number so for example the argument would be
version_2 and after the function it would change it to version_3
just increments by one
in java I would just create a new string, and grab the last character update by one and append but not sure how to do it in bash.
updateVersion() {
version=$1
}
the prefix can be anything for example it can be dog12 or dog_12 and always has one number to update.
after the update it would be dog13 or dog_13 respectively.
$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.
The operator "%" will try to remove the shortest text matching the pattern, while "%%" tries to do it with the longest text matching. Follow this answer to receive notifications.
According to this resource , when used with the printf command, “%s” Interprets the associated argument literally as string. How does shell (bash) in Linux work? I think shell is an interface which takes the commands we type in the terminal and searches the inbuilt command in bin and executes the output.
updateVersion()
{
[[ $1 =~ ([^0-9]*)([0-9]+) ]] || { echo 'invalid input'; exit; }
echo "${BASH_REMATCH[1]}$(( ${BASH_REMATCH[2]} + 1 ))"
}
# Usage
updateVersion version_11 # output: version_12
updateVersion version11 # output: version12
updateVersion something_else123 # output: something_else124
updateVersion "with spaces 99" # output: with spaces 100
# Putting it in a variable
v2="$(updateVersion version2)"
echo "$v2" # output: version3
Use parameter expansion:
#! /bin/bash
shopt -s extglob
for version in version_1 version_19 version_34.14 ; do
echo $version
v=${version##*[^0-9]}
((++v))
echo ${version%%+([0-9])}$v
done
extglob
is needed for the +([0-9])
construct which means "one or more digits".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With