2016-01-10 52 views
0

我創建了一個具有1個必需參數的shell腳本。我需要它,以便腳本只在該參數存在時運行,否則它將退出。檢查命令行參數是否存在

這裏是我的代碼:

#!/bin/bash 

branch=stable 

# Custom options/arguments 
usage() { # usage code } 

while getopts ":bs:" opt; do 
    case $opt in 
     b) 
      branch=development 
      ;; 
     s) 
      site=${OPTARG} 
      ;; 
     *) 
      usage 
      ;; 
    esac 
done 

shift $((OPTIND-1)) 

if [ -z "${s}" ]; then 
    echo " 
     $(tput setaf 1)ERROR: 
     =========================$(tput sgr0) 
     $(tput setaf 6)No website name provided: 
      Format: <example.com>$(tput sgr0) 
    " 
    exit 1; 
fi 

# Rest of the code to run when there are no errors - not putting here as it's irrelevant 

所以我希望,當我運行sudo ./nginx-install.sh會看到沒有參數,並顯示錯誤消息 - 這是不。但是,當我做sudo ./nginx-install.sh -s example.com我只是再次收到錯誤消息,當我真的希望剩下的代碼運行。

任何人都可以指出我在代碼中出錯的地方嗎?我是bash腳本編寫新手,所以主要是在Google搜索幫助中進行回覆。

謝謝。

回答

0

你把值賦給$site,不$s。變量$s一直保持空白。

+0

謝謝@choroba - 我不遠處! –