我有一个python脚本,它输出一个长长的文件列表。
脚本是从bash运行的,最后我需要将最后三个文件分配给一个特定的变量。
我能够将输出捕获到bash变量中,但是当我尝试将其输送到“tail”命令时,它似乎只有一行吗?
我已经试过了一些技巧,但似乎无法弄清楚如何在单个行的基础上使用输出。
似乎任何python输出都将被解释为一行?
echo "TESTING sample multi-line python output"
OUTPUT=$(python -c "for i in range(5): print(i)")
# check output
echo "$OUTPUT"
variable3=$(echo $OUTPUT | tail -1)
echo "VARIABLE CAPTURED"
echo $variable3我得到的是:

但实际上,我需要将variable1从末尾捕获为第3行,将variable2从末尾捕获为第2行,将variable3从末尾捕获为第一行。
因此,在上面的示例中,最后期望的结果是:
variable1 = 2
variable2 = 3
variable3 = 4为了将这些变量传递到脚本的下一阶段.
发布于 2022-02-12 23:35:05
你必须得到正确的报价,这将把4分配给variable3
variable3="$(echo "$OUTPUT" | tail -1)"
echo "$variable3"类似地,要获得variable2
variable2="$(echo "$OUTPUT" | tail -2 | head -1)"和variable1
variable1="$(echo "$OUTPUT" | tail -3 | head -1)"总之,您的脚本应该是:
#!/usr/bin/env bash
echo "TESTING sample multi-line python output"
OUTPUT="$(python -c "for i in range(5): print(i)")"
# check output
echo "$OUTPUT"
variable3="$(echo "$OUTPUT" | tail -1)"
variable2="$(echo "$OUTPUT" | tail -2 | head -1)"
variable1="$(echo "$OUTPUT" | tail -3 | head -1)"
echo variable1: "$variable1"
echo variable2: "$variable2"
echo variable3: "$variable3"发布于 2022-02-12 23:37:13
因此,我无法解释为什么会这样,但似乎print用'\n'分隔线,tail用\n\r分隔线。所以我换了几行
echo "TESTING sample multi-line python output"
OUTPUT=$(python -c "for i in range(5): print(str(i) + '\n\r', end='')")
# check output
echo "$OUTPUT"
variable3=$(echo $OUTPUT | tail -1)
echo "VARIABLE CAPTURED"
echo $variable3这将导致
TESTING sample multi-line python output
0
1
2
3
4
VARIABLE CAPTURED
4 发布于 2022-02-12 23:47:04
一个选项可以是tail -3并将最后的行读入数组中:
#!/bin/bash
echo "TESTING sample multi-line python output"
readarray -t arr <<< "$(python -c "for i in range(5): print(i)" | tail -3)"
echo "VARIABLE CAPTURED"
echo "${arr[0]}"
echo "${arr[1]}"
echo "${arr[2]}"
echo "VIA LOOP"
for var in "${arr[@]}"; do
echo "$var"
done输出
TESTING sample multi-line python output
VARIABLE CAPTURED
2
3
4
VIA LOOP
2
3
4如果您确实需要在提取最后三行之前保存完整的输出:
OUTPUT="$(python -c "for i in range(5): print(i)")"
readarray -t arr <<< "$(echo "$OUTPUT" | tail -3)"https://stackoverflow.com/questions/71096697
复制相似问题