(NOTE: this is a bash question, not k8s)
I have a working script which will fetch the name
admin-job-0
from a list of kubernetes cronjobs, of which there can be up to 32 ie. admin-job-0 -1, -2, -3 ... -31
Question: How do I grep "-$1$"
ie a dash, the number, and no more, instead of just the number as I have below?
Bonus question: Is there any way to do what I'm doing below without the if/else
logic regardless of whether there's an argument passed?
fetch-admin-job() {
if [[ -n $1 ]]; then
name=$(kubectl get cronjob | awk '/^admin-job.*/{print $1}' | grep $1 )
else
# get the first one (if any)
name=$(kubectl get cronjob | awk '/^admin-job.*/{print $1}')
fi
echo $name
}
#example:
fetch-admin-job 0
CodePudding user response:
You can replace your function code with this:
fetch-admin-job() {
kubectl get cronjob |
awk -v n="$1" '!n || $1 == "admin-job-" n {print $1}'
}
Then invoke it as:
fetch-admin-job 0
fetch-admin-job 4
fetch-admin-job
We are using this condition in awk
:
!n
: will be true when you don't pass anything in first argument||
: OR$1 == "admin-job-" n
: Will be used to compare first column in output ofkubectl
command with first argument you pass. Note that this is equivalent ofawk '/^admin-job/ ...' | grep "-$1$"
.- You don't need to use
grep
on anawk
output asawk
can handle that part as well.
CodePudding user response:
If you pass to grep a double-hyphen (--
), this signals the end of the option and a dash at the start of the pattern does not harm, i.e.
grep -- "$1"