红穆笔记

test

檢查文件類型,比較數值。 如果條件評估爲真,則返回 0,如果評估爲假,則返回 1。 另請參閱:`[`

100% 瀏覽器本地處理 0 數據上傳

常用示例

測試指定的變量是否等於指定的字符串

test "{{$MY_VAR}}" = "{{/bin/zsh}}"

測試指定的變量是否爲空([z]ero 長度)

test -z "{{$GIT_BRANCH}}"

測試指定的文件是否存在([f]ile)

test -f "{{路徑/到/文件}}"

測試指定的目錄是否不存在([d]irectory)

test ! -d "{{路徑/到/目錄}}"

如果 A 爲真,則執行 B,如果出錯則執行 C(請注意,即使 A 失敗,C 也可能會運行)

test {{condition}} && {{echo "true"}} || {{echo "false"}}

在條件語句中使用 `test`

if test -f "{{路徑/到/文件}}"; then echo "文件存在"; else echo "文件不存在"; fi

提示:花括號{{…}}是需要替換的參數(路徑、文件名等);命令只在本機終端執行,本站不保存任何輸入。

英文原文對照

展開英文說明與示例(來源 tldr-pages)

Check file types and compare values. Returns 0 if the condition evaluates to true, 1 if it evaluates to false. See also: `[`. More information

Test if a given variable is equal to a given string

test "{{$MY_VAR}}" = "{{/bin/zsh}}"

Test if a given variable is empty ([z]ero length)

test -z "{{$GIT_BRANCH}}"

Test if a [f]ile exists

test -f "{{path/to/file}}"

Test if a [d]irectory does not exist

test ! -d "{{path/to/directory}}"

If A is true, then do B, or C in the case of an error (notice that C may run even if A fails)

test {{condition}} && {{echo "true"}} || {{echo "false"}}

Use `test` in a conditional statement

if test -f "{{path/to/file}}"; then echo "File exists"; else echo "File does not exist"; fi

命令信息

命令名test
用途檢查文件類型,比較數值。 如果條件評估爲真,則返回 0,如果評估爲假,則返回 1。 另請參閱:`[`
適用平臺通用
示例數量6 條
官方文檔https://www.gnu.org/software/coreutils/manual/html_node/test-invocation.html
數據來源tldr-pages(CC-BY-4.0)· 社區中文翻譯

常見問題

test 命令是做什麼的?

檢查文件類型,比較數值。 如果條件評估爲真,則返回 0,如果評估爲假,則返回 1。 另請參閱:`[`

test 怎麼用?

頁面按場景列出了6 條常用示例:每條示例先說明用途,再給出可直接複製的完整命令(花括號裏是需要替換的參數)。

test 最常用的操作是什麼?

測試指定的變量是否等於指定的字符串:test "{{$MY_VAR}}" = "{{/bin/zsh}}"

命令裏的花括號是什麼意思?

花括號{{…}}表示需要替換成你自己的值,例如路徑、文件名;同名參數方括號(如 [-C|--directory])表示可選寫法。