简体   繁体   中英

How to execute Terminal commands from a shell script? (MacOS 10.12)

I am writing a piece of shell scripting code in an effort to automate a set of Terminal tasks on my Mac. The program executes in the Mac Terminal, but the nested commands in the if-statements do not execute when any of the if-statements are true. Any suggestions?

#!/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

Spaces are missing around the equals in the conditions.

#!/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

Thanks to the help on this forum, I was able to solve the problem. Here is the block of code that works now:

#!/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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM