3 回答
TA貢獻1906條經驗 獲得超10個贊
我總是試圖堅持使用POSIX sh而不是使用bash擴展,因為腳本的一個主要點是可移植性。(除了連接程序,不替換它們)
在sh中,有一種簡單的方法來檢查“is-prefix”條件。
case $HOST in node*)
your code here
esac
考慮到多大年齡,神秘和苛刻的sh(并且bash不是治愈:它更復雜,更不一致,更不便攜),我想指出一個非常好的功能方面:雖然一些語法元素case是內置的,結果構造與任何其他工作沒有什么不同。它們可以以相同的方式組成:
if case $HOST in node*) true;; *) false;; esac; then
your code here
fi
甚至更短
if case $HOST in node*) ;; *) false;; esac; then
your code here
fi
或者甚至更短(只呈現!為一個語言元素-但是這是不好的風格現在)
if ! case $HOST in node*) false;; esac; then
your code here
fi
如果您喜歡明確,請構建自己的語言元素:
beginswith() { case $2 in "$1"*) true;; *) false;; esac; }
這不是很好嗎?
if beginswith node "$HOST"; then
your code here
fi
由于sh基本上只是作業和字符串列表(以及內部進程,其中包含作業),我們現在甚至可以進行一些輕量級函數編程:
beginswith() { case $2 in "$1"*) true;; *) false;; esac; }
checkresult() { if [ $? = 0 ]; then echo TRUE; else echo FALSE; fi; }
all() {
test=$1; shift
for i in "$@"; do
$test "$i" || return
done
}
all "beginswith x" x xy xyz ; checkresult # prints TRUE
all "beginswith x" x xy abc ; checkresult # prints FALSE
這很優雅。并不是說我會主張使用sh來處理任何嚴重的事情 - 它在現實世界的要求上打得太快(沒有lambda,所以必須使用字符串。但是用字符串嵌套函數調用是不可能的,管道是不可能的......)
- 3 回答
- 0 關注
- 1482 瀏覽
添加回答
舉報
