I have a multiline string and I want it first to be formatted to specific length per line before passing each line to a function for line processing.


    This script should be run on a newly created server. 

    However it can also be re-run selectively even afterwards, to re configure your settings if they were messed up.

    Ready to configure the server for the first time.
echo "$description" | fmt -w 80 

I want to now iterate through the output of the above and send each line to a function.

What I imagine is something like this (which does not work):

function testme() {
  for var in "$@"
      echo "$var"
echo "$description" | fmt -w 80 | testme 

Any ideas?

  • for starters, maybe you want to reconsider your function name: test is a shell builtin, and a program at /usr/bin/test – matsib.dev May 24 '19 at 23:31
  • Thanks. will modify. – conanDrum May 24 '19 at 23:33
  • You could get rid of echo and just use here-doc structure. fmt reads stdin with no file specified, so using heredoc should be close enough to a pipe. In fact in some shells, I believe dash, heredoc is implemented as anonymous pipe – Sergiy Kolodyazhnyy May 25 '19 at 0:11

Try this way:

function testme() {
  while IFS='' read line
      echo "$line"
echo "$description" | fmt -w 80 | testme
|improve this answer|||||
  • Works but loses the formatting. Can we retain format? – conanDrum May 24 '19 at 23:37
  • Similarly but using arguments, function testme() { for var in "$@" do echo ">>> $var" done } export -f testme echo "$description" | fmt -w 80 | xargs -n 1 -P 10 -I {} bash -c 'testme "$@"' _ {} This also loses format. But also loses empty lines. – conanDrum May 24 '19 at 23:44
  • I've made a little mod: try now – matsib.dev May 24 '19 at 23:44
  • excellent... How may points can I give you?? ))) – conanDrum May 24 '19 at 23:45
  • I've made another little, but important mod; now is better: use this one instead. – matsib.dev May 24 '19 at 23:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.