首页 > 解决方案 > 如何使用 bash 输出给定输入的命令链结果

问题描述

关于这个问题,我仍然在努力使用以下单线工作

kubectl get ns | while read -r line; do  echo `$line | grep Term | cut -d' ' -f1`; done

我希望打印出结果$line | grep Term | cut -d' ' -f1但是它打印出一个空行(echo)然后执行结果$line | grep Term | cut -d' ' -f1

bash: NAME: command not found

bash: cert-manager: command not found

bash: configmap-4262: command not found

bash: configmap-4430: command not found

结果相同,但方法略有不同:

kubectl get ns | while read -r line; do ns=`$line | grep Term | cut -d' ' -f1`; echo $ns; done

我真正想要实现的是使用结果$line | grep Term | cut -d'作为shell脚本的输入,例如

do ns=`$line | grep Term | cut -d' ' -f1`; ./delete-kube-ns.sh $ns;

或者

$line | grep Term | cut -d' ' -f1` | xargs ./delete-kube-ns.sh

标签: bash

解决方案


摆脱反引号。它试图以kubectlshell 命令的形式执行输出。您想要 echo $line,而不是作为命令执行它的结果。

kubectl get ns | while read -r line; do  
    echo "$line" | grep Term | cut -d' ' -f1
done

似乎根本不需要使用while read,只需管道kubectlgrep

kubectl get ns | grep Term | cut -d' ' -f1

推荐阅读