簡體   English   中英

將 python output 的最后三行分配給 bash 中的 3 個變量

[英]getting last three lines of python output assigned to 3 variables in bash

我有一個 python 腳本,它輸出一長串文件。

該腳本從 bash 運行,最后我需要將最后三個文件分別分配給特定變量。

我能夠將 output 捕獲到 bash 變量中,但是當我嘗試將 pipe 捕獲到“tail”命令時,它似乎只有一行?

我已經嘗試過我周圍看到的技巧,但似乎無法弄清楚如何使用 output 在單獨的線路上工作。

似乎任何 python output 都會被解釋為一行?


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

為了將這些變量傳遞到腳本的下一階段...

您必須正確引用,這會將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"

所以我無法解釋為什么會這樣,但似乎 pythons 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 

一種選擇是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

Output

TESTING sample multi-line python output
VARIABLE CAPTURED
2
3
4
VIA LOOP
2
3
4

如果您真的需要在提取最后三行之前保存完整的 output:

OUTPUT="$(python -c "for i in range(5): print(i)")"
readarray -t arr <<< "$(echo "$OUTPUT" | tail -3)"

當您不需要當前環境時,可以使用set
當你想使用變量名variable#時,你需要復制它們。

set -- $( python -c "for i in range(5): print(i)"| tail -3)
variable1="$1"; variable2="$2"; variable3="$3"
# In my environment I can check the results with
set | grep "^variable.="

另一種選擇是將它們讀入變量:

read -rd "\n" variable1 variable2 variable3 < <(
  python -c "for i in range(5): print(i)"| tail -3
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM