Home > Software engineering >  Command substitution into pipe
Command substitution into pipe

Time:04-26

I have a function

function list_all () {
    output=$(sort lastb.txt | tail  2 | head -n -2 | sort | uniq -f3 | tr -s " " | cut -d' ' -f1,3,5,6)
    echo "$output"
}

I have a second function

function filter_username () {
    read -p "Enter filter: " filter
    output=$(list_all) | grep "^$filter")
    echo "$output"
}

Is it possible to assign the output variable the output of list_all piped into grep? So that I don't have to repeat the whole job I made in list_all?

CodePudding user response:

list_all is a function that writes to standard output; as such, it can be used as the input to grep by itself.

filter_username() {
    read -p "Enter filter: " filter
    output=$(list_all | grep "^$filter")
    echo "$output"
}

Note that you don't need command substitutions in either case if you are only going to immediately write the contents of output to standard output and do nothing else with it.

list_all () {
    sort lastb.txt | tail  2 | head -n -2 | sort | uniq -f3 | tr -s " " | cut -d' ' -f1,3,5,6
}

filter_username () {
    read -p "Enter filter: " filter
    list_all | grep "^$filter"
}
  •  Tags:  
  • bash
  • Related