This is the second part of a series introducing Bash programmers to Go. This part is about basics of writing CLI tools in Go. See the first part for the language building blocks. Our first CLI tool Bash is often used to write small CLI tools and automation. Let's start with an example CLI tool that prints "hello" to terminal. The Bash version is pretty simple: #! /bin/bash echo hello Now, let's implement a Go version. We start by creating a directory where the first version of our program will live. We also initialize a module in there: $ mkdir -p hello/1 $ cd hello/1 $ go mod init hello Since the program is not complex we don't have to think a lot about its design and can easily start with a test: // hello/1/hello_test.go package hello_test import ( "hello" "testing" ) func TestPrintExists ( t * testing. T ) { hello . Print () } We named the package hello_test instead of hello . This is possible and it allows for writing tests that use only the public API (identifiers starting with a capital letter) of the tested package as a real user would. In this test we just call the Print function from the hello package. Let's try and run the test: $ go test hello: no non-test Go files in ~ /github.com/go-monk/from-bash-to-go-series/part-ii-cli-tools/hello/1 FAIL hello [build failed] Yes, we have not yet written the code we want to test. So let's do it: // hello/1/hello.go package hello func Print () {} If we re-run the test $ go test PASS ok hello 0.570s we can see that all is good now. Or is it? Well, something must be wrong because an empty function that does nothing at all (except that it exists) passes the test. So the test is obviously wrong. Now we need to start thinking a bit. What should be actually tested? Making it testable Okay, we want the function to print the string "hello" to terminal. How to test it except by looking at the terminal? In Bash the terminal is the standard output, i.e. the place where the stuff is written to by default. But we can redirect the s...
First seen: 2025-09-09 18:04
Last seen: 2025-09-10 07:07