Returning a boolean from a Bash function

前端 未结 10 993
余生分开走
余生分开走 2020-12-07 07:02

I want to write a bash function that check if a file has certain properties and returns true or false. Then I can use it in my scripts in the \"if\". But what should I retur

10条回答
  •  攒了一身酷
    2020-12-07 08:02

    Be careful when checking directory only with option -d !
    if variable $1 is empty the check will still be successfull. To be sure, check also that the variable is not empty.

    #! /bin/bash
    
    is_directory(){
    
        if [[ -d $1 ]] && [[ -n $1 ]] ; then
            return 0
        else
            return 1
        fi
    
    }
    
    
    #Test
    if is_directory $1 ; then
        echo "Directory exist"
    else
        echo "Directory does not exist!" 
    fi
    

提交回复
热议问题