運行shell報錯:[: !-d: unary operator expected

運行shell報錯:[: !-d: unary operator expected

今日在編寫shell測試的時候,使用到了if 的邏輯判斷語句,然後在進行判斷一個文件(或目錄)是否存在的時候,shell無法進行運行,並報錯。

報錯原因:語法錯誤

在進行使用shell 的一些邏輯判斷是,有些語句必須前後加空格,有些則必須不能加空格,所以,這次我就吃了大虧。

#!/bin/bash     
#by author dhy    
#test -f -d    
   
DIR="./test"    

if [ !-d $DIR ]      # 報錯位置                                                 
then    
  echo "this dir is not exist!"    
  mkdir $DIR    
else    
  echo "this dir is exist! exit"    
fi 

在這裏插入圖片描述

報錯位置:if [ !-d $DIR ]需要在!和-d之間加空格

#!/bin/bash     
#by author dhy    
#test -f -d    
   
DIR="./test"    

if [ ! -d $DIR ]      # 需要加空格,注意                                                
then    
  echo "this dir is not exist!"    
  mkdir $DIR    
else    
  echo "this dir is exist! exit"    
fi 

運行成功#!
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章