BASH: how to perform arithmetic on numbers in a pipe

echo 1 2 3 4 5|{
  read line; 
  for i in $line;
  do
    echo -n "$((i * i)) "; 
  done; 
  echo
}

The {} creates a grouping. You could instead create a script for that.


I'd write:

echo "1 2 3 4 5" | {
  for N in $(cat); do
    echo $((N ** 2))
  done | xargs
}

We can think of it as a "map" (functional programming). There are a lot of ways of writing a "map" function in bash (using stdin, function args, ...), for example:

map_stdin() {
  local FUNCTION=$1
  while read LINE; do
    $FUNCTION $LINE
  done
}

square() { echo "$(($1 * $1))"; }

$ echo "1 2 3 4 5" | xargs -n1 | map_stdin square | xargs
1 4 9 16 25