How to get count of published posts in Hugo ?
in Hugo, we can get the count of published posts using the hugo commandline tool.
straight forward way ๐
We can get a list of all published posts using this command:
hugo list published
So, we can pipe this list of published posts into a tool to count lines like this.
hugo list published | wc -l
But wc -l
counts all lines including the first line which has the titles/headers. So the count of published posts is the count shown after substracting one.
count accurately ๐
One way of counting accurately is to minus one from the count like this.
echo "$(hugo list published | wc -l)-1" | bc
But there is a better way - IMO. Just skip the first row of headers, and count the rest. Here is the command to do so:
hugo list published | tail +2 | wc -l
work around ๐
We can count the published posts using a work around.
we can get count of all posts using this command:
hugo list all | wc -l
and we can get count of all unpublished posts (or drafts) using this command:
hugo list drafts | wc -l
So we can substitute count of drafts from the count of all posts to get the count of published posts.
In Bash, Zsh, or Fish shell:
echo "$(hugo list all | wc -l)-$(hugo list drafts | wc -l)" | bc
comparing both approaches ๐
~/p/abanoubhanna (main)
โญ echo "$(hugo list published | wc -l)-1" | bc
1014
~/p/abanoubhanna (main)
โญ hugo list published | tail +2 | wc -l
1014
~/p/abanoubhanna (main)
โญ echo "$(hugo list all | wc -l)-$(hugo list drafts | wc -l)" | bc
1014
~/p/abanoubhanna (main)
โญ
So, the three approaches result in the same count of published posts.
I hope you enjoyed reading this post as much as I enjoyed writing it. If you know a person who can benefit from this information, send them a link of this post. If you want to get notified about new posts, follow me on YouTube , Twitter (x) , LinkedIn , and GitHub .