查尋 Script 中變數是否定義
本函數可以檢查指定的變數是否有被定義過。
#!/bin/sh is_defined(){ varname="$1" if set | grep -q "^${varname}=";then echo "${varname} is defined." else echo "${varname} is NOT defined." fi } ### 測試函數 is_defined foo="" //定義變數 foo 為空值 is_defined "PATH" //檢查 PATH 是否被定義 is_defined "foo" //檢查 foo 是否被定義 is_defined "bar" //檢查 bar 是否被定義 unset foo //取消 foo 定義 is_defined "foo" //再次檢查 foo
執行結果顯示
PATH is defined. foo is defined. bar is NOT defined. foo is NOT defined. //因為取消 foo 定義所以再次檢查時會發現 foo 沒被定義