Saturday, July 23, 2022

[SOLVED] grep match a concat of variable and string (dash) in piped input

Issue

(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

Solution

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"

or

grep -- "$1$"

or whatever you want to achieve.



Answered By - user1934428
Answer Checked By - Terry (WPSolving Volunteer)