我正在从一个shell命令获得输出,并希望将匹配行的第一列合并到第二个命令中。这就是我所拥有的,并且它是有效的:
kubectl get pods -n system | while read string; do
if [[ "$string" == my-pod-* && "$string" == *Running* ]]; then
# echo $string
read -ra ADDR <<< "$string"
echo
echo "--- Reading logs for ${ADDR[0]} ---"
# desired output: kubectl -n system logs my-pod-123 --tail=5 -f
kubectl -n system logs ${ADDR[0]} --tail=5 -f
fi
done第一个命令的输出如下所示:
name status namespace running
my-pod-123 Running system 4h31m #<<I want this one
another-pod-5 Running system 5h15m
my-pod-023 Terminating system 8h05m假设输出只包含一个匹配项,有没有一种更短的方法来避免像这样的循环呢?提前感谢你帮助我提高我的Bash技巧,因为这看起来很笨拙。
发布于 2021-05-06 05:57:22
您可以像这样使用awk:
name=$(kubectl get pods -n system | awk '/^my-pod.*Running/{print $1}')
[[ -n $name ]] && kubectl -n system logs "$name" --tail=5 -fawk命令将匹配一行开头的模式my-pod.*Running,如果找到,将打印第一列。我们将其存储在变量name中。
如果$name不为空,则使用该值调用kubectl -n system logs。
发布于 2021-05-06 05:48:04
grep怎么样?
wanted=$(kubectl get pods -n system | grep 'my-pod-.*Running')可以同时进行错误检查:
if ! wanted=$(kubectl get pods -n system | grep 'my-pod-.*Running'); then
echo "Error: no running my-pods" >&2
fihttps://stackoverflow.com/questions/67409051
复制相似问题