純 POSIX sh 實作各種功能

看到「pure sh bible」這篇,講純 POSIX 的 sh 可以怎麼實作各種功能,Hacker News 上的討論在「Pure Sh Bible (github.com/dylanaraps)」這邊。

一般我在寫 cross platform 的 shell script 時候會假設是 POSIX environment,而不是只有 POSIX sh 硬扛,所以還是有 awkgrepsed 這類工具可以用... 而這篇裡面提到的方法有些很明顯是硬扛過去的 XD

不過裡面還是有些章節是應該要熟悉的,像是對 string 的處理算是蠻好用的,不需要拿 sed 出來用。

另外可以用 bash 的話,有很多東西會好寫很多,但開頭的 #!/bin/bashFreeBSD 上會因為 bash 會裝到 /usr/local/bin/bash,就不是很好搞... 一個解法是用 /usr/bin/env bashPATH 找,但也不是完全保險的方法 (PATH 有時候會清空...)。

FreeBSD 把 root 預設的 shell 改成 /bin/sh

Hacker News 首頁上看到 FreeBSD 把 root 的 shell 從 /bin/csh 換成 /bin/sh 了:「sh(1): make it the default shell for the root user」,Hacker News 上的討論也可以看一看:「FreeBSD switches the default root shell from csh to sh (freebsd.org)」。

依照說明是把 FreeBSD 的 /bin/sh 加上了不少東西,所以算是堪用了:

In the recent history sh(1) has gain the missing features for it to
become a usable interractive shell:
- command completion
- persistent history support
- improvements on the default bindings in emacs mode
- improvements in the vi mode (repect $EDITOR)
- print a newline when exiting via ^D
- default prompt and improvements on how PS1 can be configured
- and more.

This changes also simplifies making tiny freebsd images with only sh(1)
as a shell

以前也是用 csh 系列的 (像是 tcsh),後來開始用 Linux 就往 BashZsh 定居了...

關於各家 ACME client (或者說 Let's Encrypt client?)

在「Another free CA as an alternative to Let's Encrypt (scotthelme.co.uk)」這邊引用的文章本來在討論又多了一家免費的 SSL certificate 可以用,但結果討論的主力都在講除了 Certbot 外還有什麼比較好用...

大家之所以厭惡 Certbot,先不講他需要依賴一堆 Python 的套件包,最主要的問題在於現在 Certbot 官方建議的指引裡面都要求你裝 Snap,而 Snap 這東西超級吃資源...

既然是資源問題,裡面可以看到 Dehydrated 又被拿出來推薦了,另外也有提到 acme.sh,不過我個人不太愛 acme.sh,主要是預設值跑去用 ZeroSSL 的 CA。

這種單檔就可以跑的很適合包進像是 Ansible 這類的管理工具,至少目前用起來沒什麼大問題...

Bash Script 的好習慣

這篇給了一份 bash script 用的 tempalte,但更重要的反而是裡面提到的 best practice:「Minimal safe Bash script template」。

首先是不要寫 /bin/bash 這件事情,因為有些系統是沒有 /bin/bash 的,像是 FreeBSD

如果程式是可以用 POSIX sh 語法的話,應該優先考慮 /bin/sh,如果用到非 POSIX 標準的語法的話,用 env 帶出來會少一些問題:

#!/usr/bin/env bash

再來是 fail 時就趕快停止,不要再往下執行,這點算是老生常談了,文章作者也有給一個範例說明:

set -Eeuo pipefail

再來另外一個還蠻有用的事情是攔下常見的 signal 處理「後事」:

trap cleanup SIGINT SIGTERM ERR EXIT

cleanup() {
  trap - SIGINT SIGTERM ERR EXIT
  # script cleanup here
}

其他的可以看一看,但未必要全盤收下...

第二堂:「Shell Tools and Scripting」

這個系列是從『MIT 的「The Missing Semester of Your CS Education」』這邊延伸出來的,這篇文章講第二堂課「Shell Tools and Scripting」。

這堂有點像是第一堂的延伸,在講更多 shell 的操作與工具,然後說明 shell script 怎麼寫。

開頭就先說明有 function,然後講了不少 magic variable,像是 $0$1$9,而 $@$# 也提到了 (但居然沒提到 $*),然後再來是 $$!!$_

然後提到 true 與 false,接著就講條件 || 與 && 了。後面就開始講 shell 裡面的 for 與 if,基本上到這邊已經能寫不少東西了?

後面就介紹更多工具...

另外一套用 shell script 寫的 ACME client (或者說 Let's Encrypt client)

acme.sh 是另外一套用 shell script 寫的 ACME client,由西安的 Neilpang 寫的。我也包成 Ubuntu PPA 了:「PPA for acme.sh」。

我建議的用法是先建立 /etc/acme.sh,把各種設定都放到這個目錄裡面,然後用這樣的指令執行:

$ sudo acme.sh --issue -d www.example.com -w /srv/www.example.com/webroot/ --home /etc/acme.sh/

不過 acme.sh 有個問題,沒有將檔案與目錄權限處理好... 我申請完後發現目錄是 drwxr-xr-x,而 key 是 -rwxr-xr-x,這樣會有安全性的問題,需要自己再修改。