Home > Mobile >  Bash function can indent piped lines multiple times without waiting for whole input
Bash function can indent piped lines multiple times without waiting for whole input

Time:12-11

What I want to achieve:

  • Define a function that can be used to pipe input, such as echo input | my_function
  • This function modifies every inputted line, e.g., it adds indentation at the beginning.
  • This function can be reused twice and in that case does its modification (double indent) twice, e.g. echo input | my_function | my_function results in \t\tinput.
  • This function does not wait for whole input to be supplied, it can print out the line directly without seeing all input.

As my test, please see the following script:

#!/usr/bin/env bash

main() {
  echo 'first:'
  echo 'once' | tab_indent_to_right
  echo 'twice' | tab_indent_to_right | tab_indent_to_right
  {
    echo 'wait 2 sec'
    sleep 2
    echo 'wait 2 sec'
    sleep 2
    echo 'waited'
  } | tab_indent_to_right
}

tab_indent_to_right() {
  # while read -r line; do echo $'\t'"$line"; done  #            
  • Related