Yevhenii Nadtochii
Yevhenii Nadtochii

Reputation: 704

How to put a while-loop construction into a variable?

I have a command1 doing something useful, for example:

command1="ls /home/yevhenii"

And I also have a while-loop that consumes the output of command1 and produces its own:

$command1 | while read line;
    do 
        echo "   ${line/[1G/[4G}" 
    done

But I want to unify my script and put all the commands in the corresponding variables, so to be able to write something like this:

$command1 | $command2 | ...

Do I have any options in order to achieve that ?

Upvotes: 0

Views: 56

Answers (1)

Socowi
Socowi

Reputation: 27185

As pointed out in the comments, use functions:

#! /usr/bin/env bash

command1() {
  ls /home/yevhenii
}

command2() {
  while read line; do
    echo "   ${line/[1G/[4G}" 
  done
}

command1 | command2

That aside, you might want to drop ls dir | while read line in favor of for line in dir/*. See Why you shouldn't parse the output of ls.

Upvotes: 3

Related Questions