Search code examples
bashps

Why is the ps format option '%a' truncated?


I'm trying to read the output of ps using a custom format specified with -o. Because I want to specify a custom separator I'm using AIX format descriptors (e.g. %p for pid, %a for args etc), but the same issue is seen when using the normal formatting codes.

When I specify %a at the end of this format string, all works as expected:

$ echo 'while true; do sleep 1; done' > really-really-really-long-filename 

$ bash really-really-really-long-filename &
[1] 31181

$ ps -p 31181 -o '%p|%a'

  PID|COMMAND
31181|bash really-really-really-long-filename

However if %a is not the last field, I get this:

$ ps -p 31181 -o '%a|%p'

COMMAND                    |  PID
bash really-really-really-l|31181

This doesn't seem to be related to any screen-width modifiers. Is there something else at play here?

(GNU bash 4.1.5)


Solution

  • Perhaps not the most elegant solution, but you could mix and match formats just so you can use width control for selected fields. E.g.

    [me@home]$ ps -p 780 -o "%a|%p"
    COMMAND                    |  PID
    dbus-daemon --system --fork|  780
    
    [me@home]$ ps -p 780 -o args:50 -o "|%p"
    COMMAND                                           |  PID
    dbus-daemon --system --fork --activation=upstart  |  780
    

    As for why the truncation happens, my guess is there's a hardcoded width that is used for each field (unless a width is specified by the user) when it is not the last field. This saves the program having to first buffer the output to determine the maximum column width before printing.

    In the case of args the default hardcoded width seems to be 27 (see this implementation of ps).

    I should mention that this is just a purely speculation on my part and may not necessarily be the case.