天天看點

shell從函數檔案裡調用函數

碰到一個shell中函數調用的小問題,記錄一下。

shell中函數有三種調用方式,一種是在檔案前面定義函數,然後在以下直接調用;一種是通過加載shell,在shell中直接調用;第三種是将函數寫入檔案。然後在其它shell中調用函數。

這裡寫一下關于第三種方法的樣例:

is_it_a_directory()
{
if [ $# -lt 1 ];then
  echo "is_it_a_directory:I need an argument"
  return 1
fi

_DIRECTORY_NAME=$1
if [ ! -d $_DIRECTORY_NAME ];then
  return 1
else
  return 0
fi
}

error_msg()
{
echo -e "\007"
echo $@
echo -e "\007"
  return 0
}
      

這個檔案定義了兩個函數,我們在以下的shell中調用者兩個函數,這裡有一點須要注意,在調用之前,要加載函數檔案。加載的方式為 . /路徑。注意有個空格

#!/bin/sh
. functions.sh
echo -n "enter destination directory :"
read DIREC
if is_it_a_directory $DIREC
then :
else
  error_mag "$DIREC does not exist...creating it now"
  mkdir #DIREC > /dev/null 2>&1
  if [ $? != 0 ];
  then
    error_msg "could not "
    exit 1
  else :
  fi
fi

echo "extracting files..."