while read line; do echo $line; done <<< "$var"

Access variables inside a - piped while - loop

Consider the following simple situation [ reading something using while and read ] [See script 1 in sample output] --------------------------------------------------- The variable var is assigned with "nullll" at first. Inside the while loop [piped while] it is assigned with "whillleeee". [Onlly 2 assignments stmts]. Outside the loop the last assigned value for "var" [and no variable] inside the while can't be accessed [Due to pipe, var is executed in a sub shell]. In these type of situation variables can be accessed by modifying as follows. [See script 2 in sample output] ___________________________ Vary helpful when reading a set of items, say file names, stored on a file [or variable] to an array an use it later. Is there any other way 2 access variables inside and outside the loop ??
Sample Output
script 1
__________________
#!/bin/bash

var="nullll"
echo "var=$var"
echo
str="aa
bb
cc"

echo "$str" | while read line
do
echo "line=$line"
echo "var=$var"
var="whillleeee"

done 

echo
echo "line=$line"
echo "var=$var"



------------------------------
Output
----------------------------
var=nullll

line=aa
var=nullll
line=bb
var=whillleeee
line=cc
var=whillleeee

var=nullll
___________________________________________________________
script 2---------------------------------------------------
___________________________________________________________

#!/bin/bash

var="nullll"
echo "var=$var"
echo
str="aa
bb
cc"

while read line
do
echo "line=$line"
echo "var=$var"
var="whillleeee"

done <<< "$str"

echo
echo "var=$var"

----------------------------------
Output
------------------------------------

var=nullll

line=aa
var=nullll
line=bb
var=whillleeee
line=cc
var=whillleeee

var=whillleeee

-5
By: totti
2011-09-22 16:53:32

These Might Interest You

  • Usually the MS-DOS cmd.exe processes in the whole FOR loop as one command and expands each var like %varname% in before (except the loop var of course). This command enables expansion of other vars than only the loop var during the FOR loop. The syntax of the var to expand is then !varname! inside the FOR loop. Use command endlocal to end the setlocal command. E.g. (only works from batch files, not from commandline directly): @echo off setlocal enabledelayedexpansion FOR %%A IN (*) DO ( set file=%%A echo !file! ) endlocal


    -1
    setlocal enabledelayedexpansion
    Marco · 2010-08-10 12:26:43 2
  • With this command you can use shell variables inside sed scripts. This is useful if the script MUST remain in an external file, otherwise you can simply use an inline -e argument to sed.


    -1
    expanded_script=$(eval "echo \"$(cat ${sed_script_file})\"") && sed -e "${expanded_script}" your_input_file
    giuseppe_rota · 2009-05-07 14:21:14 0
  • This uses some tricks I found while reading the bash man page to enumerate and display all the current environment variables, including those not listed by the 'env' command which according to the bash docs are more for internal use by BASH. The main trick is the way bash will list all environment variable names when performing expansion on ${!A*}. Then the eval builtin makes it work in a loop. I created a function for this and use it instead of env. (by aliasing env). This is the function that given any parameters lists the variables that start with it. So 'aae B' would list all env variables starting wit B. And 'aae {A..Z} {a..z}' would list all variables starting with any letter of the alphabet. And 'aae TERM' would list all variables starting with TERM. aae(){ local __a __i __z;for __a in "$@";do __z=\${!${__a}*};for __i in `eval echo "${__z}"`;do echo -e "$__i: ${!__i}";done;done; } And my printenv replacement is: alias env='aae {A..Z} {a..z} "_"|sort|cat -v 2>&1 | sed "s/\\^\\[/\\\\033/g"' From: http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html Show Sample Output


    2
    for _a in {A..Z} {a..z};do _z=\${!${_a}*};for _i in `eval echo "${_z}"`;do echo -e "$_i: ${!_i}";done;done|cat -Tsv
    AskApache · 2010-10-27 07:16:54 0
  • kpartx can be found inside of the multipath-tools package -a adds the mappings and -d deletes them Show Sample Output


    1
    kpartx -a /dev/mapper/space-foobar
    flart · 2009-07-01 09:53:33 1
  • This command allows you to stream your log files, including gziped files, into one stream which can be piped to awk or some other command for analysis. Note: if your version of 'find' supports it, use: find /var/log/apache2 -name 'access.log*gz' -exec zcat {} + -or -name 'access.log*' -exec cat {} +


    0
    find /var/log/apache2 -name 'access.log*gz' -exec zcat {} \; -or -name 'access.log*' -exec cat {} \;
    recursiverse · 2010-06-19 08:35:12 0
  • This command will traverse all of the folders and subfolders under current working directory. For every file inside it, it will do a search inside the content of the file for a specific term 'what'. Then it will print a list of the lines that contain that term (and match that pattern). Each matching line will be preceded with the path and name to the file and then the line number iside taht file wehre the pattern was found. Then the actual content of the matching lien will be printed. The output will be piped throug less, so that the user can scroll through it if it goes beyond the limits of the current display window. Show Sample Output


    1
    find . -exec grep -Hn what \{\} \; | less
    ynedelchev · 2014-02-17 09:59:01 0

What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

What's this?

commandlinefu.com is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands



Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.

» http://twitter.com/commandlinefu
» http://twitter.com/commandlinefu3
» http://twitter.com/commandlinefu10

Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: