0

I have simple Bash script running command in Kubernetes, however I need autocomplete in one command to continue:

#!/bin/bash
DATE=$(date +%Y-%m-%d_%H:%M:%S)
printf "Available Kubectl contexts:\n\n"
kubectl config get-contexts -o=name | sort -n
printf "%s\n"
echo -ne "Select Kubectl context: "; read KUBE_CONTEXT
for I in $KUBE_CONTEXT ; do
    kubectl config use-context $KUBE_CONTEXT
done
echo -ne "Path to file containing Job ID list: "; read -e JOB_ID_LIST
printf "%s\n"
echo "Setting port forwarding to Prometheus POD in $KUBE_CONTEXT" ;

and this is where I need autocompletion as the pod name is different in each kubectl environment.

kubectl port-forward -n prometheus prometheus-prometheus-RANDOM_TEXT-RANDOM_TEXT 20001:9090

for instance:

kubectl port-forward -n prometheus prometheus-prometheus-6465c4df4c-4dvf7 8080:9090 &

Autocomplete works when I am typing it manually, but I want Bash to autocomplete it in the script. Is it possible?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
DisplayName
  • 479
  • 2
  • 7
  • 20
  • No, see: [Changing tab-completion for read builtin in bash](https://stackoverflow.com/q/34660459/3776858) – Cyrus Jun 20 '19 at 11:18
  • `read` can output a prompt, no need for `echo`. You should almost always use `-r` with `read`. `read -e` enables readline during input, which you've already got in your script. You can create your own completions using Bash's [programmable completion](https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion-Builtins.html). – Dennis Williamson Jun 20 '19 at 11:58

1 Answers1

0

Using interactive features of a shell in a script should be your last resort.

We can do without: Let's first get all pod names in the namespace; then filter for your desired pod name.

podName=$(kubectl get pods -n prometheus -o name | grep "^pod/prometheus-prometheus-" | cut -d/ -f2)
hnicke
  • 602
  • 4
  • 7