'Consider each line generated by a command as a line in a script

I have this simple script :

#!/bin/bash

dates_and_PID=$(ps -eo lstart,pid)

echo ${dates_and_PID::24}

And I would like each line to be cut at the 24th character. Nevertheless, it considers the variable dates_and_PID as a single line, so I only have one line that is generated. Whereas I would like it to be cut for each line.

I am practicing but the final goal would be to have the script change the dates from Mon Nov 11 2020 to 11/11/20.

Thank your for your help :)



Solution 1:[1]

You need to iterate over the input line by line, instead of reading everything into a single variable. Something like this should do the trick:

#!/bin/bash

while read line; do
  echo "${line::24}"
done < <(ps -eo lstart,pid)

Solution 2:[2]

You can pipe stdout to while loop:

ps -eo lstart,pid | while read line; do
  echo "${line::24}"
done

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cyrus
Solution 2 Weihang Jian