I’m using Docker for many of our services and the command docker ps
is essential for me but I hate the long and extensive output.
For example in this server:
[root@server docker-postgres]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
020ec906a5ed bitnami/pgpool:4 "/opt/bitnami/script…" 2 weeks ago Up 2 weeks (healthy) pgpool
d40dd0f76e19 postgres_img "docker-entrypoint.s…" 2 weeks ago Up 19 hours postgres
The only things that I look when run docker ps
are these:
pgpool Up 2 weeks (healthy)
postgres Up 19 hours
I’m able to get that output running this command:
docker ps | awk -F '[[:space:]][[:space:]]+' '{print $6,$5}' | column -t --table-right 2,3,4
But that command is very large and I tried to set an alias just like this:
alias dps="docker ps | awk -F '[[:space:]][[:space:]]+' '{print $6,$5}' | column -t --table-right 2,3,4"
But running the alias I get this result:
[root@server docker-postgres]# dps
awk: cmd. line:1: {print ,}
awk: cmd. line:1: ^ syntax error
awk: cmd. line:1: {print ,}
awk: cmd. line:1: ^ syntax error
awk: cmd. line:1: {print ,}
awk: cmd. line:1: ^ unexpected newline or end of string
I don’t know what is happening, I have tried changing several things in the alias line but no success…
4
Answers
Thanks to the suggestion of @pmf this is what I was looking for:
it gives me this result:
Don’t use an alias; use a function.
The immediate problem is that
$6
and$5
were being expanded immediately at alias-definition time, because you used double-quotes for the alias definition. Nothing inside the definition of the function is subject to shell evaluation until the function is called.Of course, the fact that
docker ls
is capable of producing the output you want without having to parse the output ofdocker ps
means you should use that instead of this pipeline.The reason your alias is failing is the incorrect quoting. You can nominally fix it by backslash-escaping any dollar signs (or double quotes, or backticks) in the alias definition:
But aliases suck anyway. Use a function instead.
Of course, in this particular case, using the
--format
option ofdocker ps
ordocker container ls
is vastly superior, like you already discovered.Perhaps notice also the
"$@"
at the end which allows you to pass in additional options or arguments.This
means 2 or more white-space characters, in GNU
AWK
you might express that more concisely by writingSee interval expression in Regexp Operators in
awk
for detailsSee