2016-09-08 192 views
0

我正在編寫一段shell腳本代碼,努力在我的Mac上自動執行一組終端任務。該程序在Mac終端中執行,但if語句中的任何if語句爲真時,if語句中的嵌套命令不會執行。有什麼建議麼?如何從shell腳本執行終端命令? (MacOS 10.12)

#!/bin/bash 

FINDER="1" 
DOCK="2" 
CAFF="3" 

echo Select an option: 
echo 1. killall Finder 
echo 2. killall Dock 
echo 3. caffeinate 

echo Enter you choice: 
read CHOICE 

if [ "$CHOICE"="$FINDER" ]; then 
    killall Finder 
elif [ "$CHOICE"="$DOCK" ]; then 
    killall Dock 
elif [ "$CHOICE"="$CAFF" ]; then 
    caffeinate 
fi 

exit 

回答

2

條件中的等號周圍缺少空格。

#!/bin/bash 

FINDER="1" 
DOCK="2" 
CAFF="3" 

echo Select an option: 
echo 1. killall Finder 
echo 2. killall Dock 
echo 3. caffeinate 

echo Enter you choice: 
read CHOICE 

if [ "$CHOICE" = "$FINDER" ]; then 
    killall Finder 
elif [ "$CHOICE" = "$DOCK" ]; then 
    killall Dock 
elif [ "$CHOICE" = "$CAFF" ]; then 
    caffeinate 
fi 
+0

好吧,我隔開了等號,但現在程序只執行if語句的第一個參數,不管我輸入到控制檯的數字是多少。 –

+0

嘗試在shebang下添加'set -x',執行時會寫入執行的命令並幫助您調試腳本。使用終端運行它。祝你好運! – GabLeRoux

0

感謝這個論壇的幫助,我解決了這個問題。下面是現在可以工作的代碼塊:

#!/bin/bash 

CHOICE=0 
FINDER=1 
DOCK=2 
CAFF=3 

echo Select an option: 
echo 1. killall Finder 
echo 2. killall Dock 
echo 3. caffeinate 

echo -n Enter your choice: 
read CHOICE 

echo You chose: $CHOICE 

if [ $CHOICE = $FINDER ]; then 
    echo Executing killall Finder… 
    killall Finder 
elif [ $CHOICE = $DOCK ]; then 
    echo Executing killall Dock…  
    killall Dock 
elif [ $CHOICE = $CAFF ]; then 
    echo Executing caffeinate… 
    caffeinate 
fi 

exit