TGStat
TGStat
Type to search
Advanced channel search
  • flag English
    Site language
    flag Russian flag English flag Uzbek
  • Sign In
  • Catalog
    Channels and groups catalog Regional compilations Thematic compilations Платные каналы Search for channels
    Add a channel/group
  • Ratings
    Rating of channels Rating of groups Posts rating
    Ratings of brands and people
  • Analytics
  • Search by posts
  • Telegram monitoring
  • Promotion
    Advertising through Yandex Business Advertising in channels through TGStat Agency Advertising on TGStat.ru website
BashTex | Linux

20 Aug, 12:15

Open in Telegram Share Report

lastpipe: как Bash меняет поведение последней команды в pipeline

Одна из особенностей Bash - команды в pipeline обычно выполняются в отдельных subshell. Из-за этого переменные, изменённые внутри while, после цикла могут не сохраниться.

Например:

count=0

printf '%s\n' a b c |
while read -r line; do
((count++))
done

echo "$count"

В некоторых случаях результатом будет 0.

Но у Bash есть настройка lastpipe, которая меняет это поведение.

▪️Включаем lastpipe

shopt -s lastpipe

Теперь последняя команда pipeline может выполняться в текущем shell.

count=0

printf '%s\n' a b c |
while read -r line; do
((count++))
done

echo "$count"

При подходящих условиях получим: 3

▪️Есть важное условие

lastpipe работает только когда job control отключён:

set +m
shopt -s lastpipe

Именно поэтому поведение может отличаться между интерактивным Bash и обычным скриптом.

▪️Проверить настройку

shopt lastpipe

Получим:

lastpipe off

или:

lastpipe on

▪️Почему это не универсальная замена

Вместо изменения поведения shell часто проще использовать редирект:

while read -r line; do
((count++))
done <

597 0 19 5
Catalog
Channels and groups catalog Channels compilations Search for channels Add a channel/group
Ratings
Rating of Telegram channels Rating of Telegram groups Posts rating Ratings of brands and people
API
API statistics Search API of posts API Callback
Our channels
@TGStat @TGStat_Chat @telepulse @TGStatAPI
Read
Академия TGStat Telegram Research 2019 Telegram Research 2021 Telegram Research 2023
Contacts
Справочный центр Support Email Jobs
Miscellaneous
Terms and conditions Privacy policy Public offer
Our bots
@TGStat_Bot @SearcheeBot @TGAlertsBot @tg_analytics_bot @TGStatChatBot