All Posts programming How to get count of published posts in Hugo ?

How to get count of published posts in Hugo ?

ยท 351 words ยท 2 minute read

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 ๐Ÿ”—

count of published posts Hugo CLI

~/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 .