Does someone know a ressource where I can easily learn how to switch from Bash to Go?
To give some context: When it comes to serious programs I use Go already, but often I just want to code a little script to watch a website for changes for example:
#!/usr/bin/env bash
url="https://example.com"
mem="memory.txt"
oldsum="$(cat "$mem")"
newsum="$(curl -sL "$url" | sha512sum)"
if [ "$oldsum" != "$newsum" ]; then
xmpp_notify "$url changed"
echo "$newsum" > "$mem"
fi
I haven't tried it yet, but in my mind it feels like writing such a program would be more time consuming/complex in Go than writing it in bash. Neverthelss, I feel like Go is overall a much better language than Bash (with all those quotes), so I would like to transition to writing more short programs in Go and for that I would like to learn how to do things like reading/writing/grepping files as easily in Go as I do it in Bash. Any idea if someone wrote some hints together already?Being such a concise language, Haskell could be a good option here. You can do quick scripting while still having a powerful type system (especially compared to Go's) backing you up. I somewhat quickly typed this code up and haven't tested it, but it should replicate that bash script pretty closely:
#!/usr/bin/env stack
-- stack script --resolver=lts-12.2
import System.Process (system)
import Control.Lens
import Crypto.Hash.SHA256
import qualified Data.Bytestring.Lazy as B
import Network.Wreq
url = "https://example.com"
mem = "memory.txt"
main = do
oldsum <- B.readFile mem
newsum <- (hashLazy . view responseBody) <$> get url
when (oldsum /== newsum) $ do
exitCode <- system $ "xmpp_notify " ++ url ++ " changed"
B.writeFile mem newsum
I didn't make use of it, but there's also the Turtle library which aims to provide a fairly solid shell scripting experience, providing a lot of coreutils as simple Haskell functions. You also get a REPL in the form of GHCI, which comes default in Haskell installations.
Haskell or Rust are the same incidentally: while the same "lexical" operator is used all the time (`+`), numeric additions are defined for two values of the exact same concrete type e.g. in Haskell you can add two Int or to Float or two Integer, but not an Int and an Integer, or an Int and a Float:
So in ghci: