LinuxQuestions.org
Share your knowledge at the LQ Wiki.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 04-30-2009, 02:38 AM   #1
Vit77
Member
 
Registered: Jun 2008
Location: Toronto, Canada
Distribution: SuSE, RHEL, Mageia
Posts: 132

Rep: Reputation: 17
bash: piped loop in same shell


Hi,

I'm trying to update variable's value in a piped loop:

Code:
a=0
txt='a\nb\nc'
echo -e "$txt" | while read line
do
  # do smth with $line ...
  a=$((a+1))
  echo $a
done

echo "Final: $a"
Result:
Code:
1
2
3
Final: 0
So, this while-loop was executed in a new shell, and original variable $a was not changed.

Is it possible to use such piped loop within the same shell, or how to keep the changed value outside?

Thanks!
 
Old 04-30-2009, 02:46 AM   #2
colucix
LQ Guru
 
Registered: Sep 2003
Location: Bologna
Distribution: CentOS 6.5 OpenSuSE 12.3
Posts: 10,509

Rep: Reputation: 1983Reputation: 1983Reputation: 1983Reputation: 1983Reputation: 1983Reputation: 1983Reputation: 1983Reputation: 1983Reputation: 1983Reputation: 1983Reputation: 1983
Use process substitution instead of the pipe:
Code:
#!/bin/bash
a=0
txt='a\nb\nc'
while read line
do
  # do smth with $line ...
  a=$((a+1))
  echo $a
done < <(echo -e "$txt")

echo "Final: $a"
this does not run the loop in a subshell and keeps the last updated value of the variable.
 
Old 04-30-2009, 02:50 AM   #3
Vit77
Member
 
Registered: Jun 2008
Location: Toronto, Canada
Distribution: SuSE, RHEL, Mageia
Posts: 132

Original Poster
Rep: Reputation: 17
It works great! Thank you!
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
nested , piped bash commands nass Programming 9 06-17-2008 06:33 AM
LXer: Piped Variable Scoping In The Linux Or Unix Shell LXer Syndicated Linux News 0 06-06-2008 04:10 AM
Using piped input in a BASH script gnashley Programming 1 08-05-2007 10:50 AM
Shell-script should control a piped command -> PROBLEM waldese Linux - General 8 09-29-2006 03:27 AM
PHP Shell Script - Read piped text dlublink Linux - Software 3 08-13-2005 01:57 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 05:34 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration