Linux真小白入門教程第二十五集 test命令

2021-09-03 02:04:43 字數 2567 閱讀 6213

if-then只能探測命令的退出狀態碼嗎?

是的但是我們還有test命令

test命令中可以對列出的條件進行判斷,如果成立,test命令就會退出並返回退出狀態碼0

test condition
和if-then一起使用時:

if test condition

then

commands

fi

注:如果不寫test命令的condition部分,它會以非零的退出狀態碼退出,並執行else語句塊。

$ cat test6.sh

#!/bin/bash

#testing the test command

#if test

then

echo "no expression returns a true"

else

echo "no expression returns a false"fi$

$ ./test6.sh

no expression returns a false

$

如果加入乙個條件,那麼會執行判斷過程

$ cat test6.sh

#!/bin/bash

#testing the test command

#my_variable="full"

#if test $my_variable

then

echo "the $my_variable expression returns a true"

else

echo "the $my_variable expression returns a false"fi$

$ ./test6.sh

the full expression returns a true

$

此時my_variable中存有資料,不為空,test命令返回退出狀態碼0。

(注:#符號作為空行標識)

除此之外,bash shell還提供了另外一種測試條件的方法

if [ condition ]

then

commands

fi

方括號中定義了測試條件test命令可以判斷三類條件: 數值比較 字串比較 檔案比較

對於數值比較,test常用的選項引數如下:

數值的條件測試可以用在數字和變數上

$ cat numeric_test.sh

#!/bin/bash

#using numeric test evaluations

#value1=10

value2=11

#if [ $value1 -gt 5 ]

then

echo "the test value $value1 is greater than 5"fi#

if [ $value1 -eq $value2 ]

then

echo "the values are equal"

else

echo "the values are different"fi#

$

執行結果如下:

$ ./numeric_test.sh

the test value 10 is greater than 5

the values are different

$

然而如果涉及到浮點值,數值條件測試就會有限制。

$ cat floating_point_test.sh

#!/bin/bash

#using floating point numbers in test evaluations

#value1=5.555

#echo "the test value is $value1"

#if [ $value1 -gt 5 ]

then

echo "the test value $value1 is greater than 5"fi#

$ ./floating_point_test.sh

the test value is 5.555

./floating_point_test.sh: line 8:

[: 5.555: integer expression expected

$

記住,bash shell只能處理整數

scikit learn小白入門教程(一)

本系列文章,將針對python機器學習庫scikit learn來展開,旨在幫助那些剛開始接觸機器學習專案,但是看不懂裡面各種模型如何使用的小夥伴。我將介紹了一些scikit learn中使用的機器學習詞彙及常用模型,並指導小夥伴們自己動手搭建 訓練自己的模型。教你訓練乙個機器學習模型 scikit...

Linux入門教程

linux下有兩種使用者 1.root使用者,提示符 2.普通使用者,提示符 在 etc目錄下有乙個inittab檔案,其中有一行配置 id 3 defualt 其中,數字3就代表一啟動進入字元終端,如果改為5則代表一啟動進入x window 修改口令 passwd 退出登入 exit 關閉機器 只...

Linux入門教程

xshell 6 ssh遠端終端工具 sftp工具 常用命令 軟體安裝 還有好多其他的都可以看看。我的環境 vmware15 linux centos6 32位 具體安裝過程看這裡 可能會遇到這個問題 用ifconfig命令,只有lo,沒有eth0的解決方案 winscp 是乙個 windows 環...