简体   繁体   中英

Learning Bash Conditionals - Syntax errors

Okay. I've been banging my head up against the Linux wall again. What am I doing incorrectly here:

#! /bin/bash
echo
echo "1. Windows (Microsoft)
echo  2. Linux (Red Hat)
echo  3. MacOS (Apple)
echo
echo -n Select your OS choice [1, 2 or 3]: "
READ OS
echo

if [ "$OS" -eq 1 ]; then
echo "You picked Windows (Microsoft)."
fi
if [ "$OS" -eq 2 ]; 
echo "You picked Linux (Red Hat)."
fi
if [ "$OS" -eq 3 ]; then
echo "You picked MacOS (Apple)."
fi
if [ "$OS" > 3 || "$OS" < 1 ]];
echo "Invalid selection!"
fi
exit 1

error message :

[ : : integer expression expected

You have used the wrong if/elif/else syntax:

if [ "$OS" -eq 1 ] 
then
    echo "You picked Windows (Microsoft)."
elif [ "$OS" -eq 2 ] 
then 
     echo "You picked Linux (Red Hat)."
elif [ "$OS" -eq 3 ] 
then
     echo "You picked MacOS (Apple)."
else 
     echo "Invalid selection!"
fi
exit 1

Also if you want to use greater or inferior, you should use -gt or -lt etc. Please refer to this page: http://tldp.org/LDP/abs/html/comparison-ops.html

also have a look at the syntax of or and and at this link: http://tldp.org/LDP/abs/html/ops.html#ANDOR

Also I have just spotted it by your should have the same number of opening square brackets than closing ones.

After fixing all the issues in the script:

#! /bin/bash

echo
echo "1. Windows (Microsoft)"
echo "2. Linux (Red Hat)"
echo "3. MacOS (Apple)"
echo
echo -n "Select your OS choice [1, 2 or 3]: "
read OS
echo

if [ "$OS" -eq 1 ] 
then
    echo "You picked Windows (Microsoft)."
elif [ "$OS" -eq 2 ] 
then 
     echo "You picked Linux (Red Hat)."
elif [ "$OS" -eq 3 ] 
then
     echo "You picked MacOS (Apple)."
else 
     echo "Invalid selection!"
fi
exit 0

Producing the following output at execution:

arobert@arobert-VirtualBox [11:48:52]
[/home/arobert/test_awk] >
./ostype.sh 

1. Windows (Microsoft)
2. Linux (Red Hat)
3. MacOS (Apple)

Select your OS choice [1, 2 or 3]: 2

You picked Linux (Red Hat).
arobert@arobert-VirtualBox [11:48:56]
[/home/arobert/test_awk] >
./ostype.sh 

1. Windows (Microsoft)
2. Linux (Red Hat)
3. MacOS (Apple)

Select your OS choice [1, 2 or 3]: 1

You picked Windows (Microsoft).
arobert@arobert-VirtualBox [11:49:00]
[/home/arobert/test_awk] >
./ostype.sh 

1. Windows (Microsoft)
2. Linux (Red Hat)
3. MacOS (Apple)

Select your OS choice [1, 2 or 3]: 3 

You picked MacOS (Apple).
arobert@arobert-VirtualBox [11:49:05]
[/home/arobert/test_awk] >
./ostype.sh 

1. Windows (Microsoft)
2. Linux (Red Hat)
3. MacOS (Apple)

Select your OS choice [1, 2 or 3]: 5

Invalid selection!

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