[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

how to write string comparison in shell script

Posted on 2008-11-06
3
Medium Priority
?
11,777 Views
Last Modified: 2013-12-26
Hi, I am writing a shell script which will input a string parameter. Inside the script I will do different action depending on the string value. I wrote

myscript:

if [ $1 == "test1" ]
then
  echo A
else
  echo B
fi

myscript  test1
A

myscript junk
B

So, this is all good

now if I change my script to

if [ $1 == "no" ]
then
  echo A
else
  echo B
fi

myscript  'asdfasdf'
B
myscript '-plll -o lll'
A

Why A?

I enter most garbage parameter to myscript it will echo B but for a few it will return A. Why?

What do I need to do to fix this? Thanks!
0
Comment
Question by:xewoox
3 Comments
 
LVL 5

Accepted Solution

by:
SmartIntel earned 600 total points
ID: 22901891
try without quotes
myscript  -plll -o lll
0
 
LVL 40

Assisted Solution

by:omarfarid
omarfarid earned 300 total points
ID: 22901956
try

#!/usr/bin/sh
if [ "$1" = "no" ]
then
  echo A
else
  echo B
fi
0
 
LVL 48

Assisted Solution

by:Tintin
Tintin earned 600 total points
ID: 22901981
The reason your second example outputs 'A' is that the if test effectively becomes

if [  -plll -o lll == 'no' ]

As -plll has no comparison, it is automatically a true value, therefore you end up with

true OR false

which is TRUE.

0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Regular patching is part of a system administrator's tasks. However, many patches require that the system be in single-user mode before they can be installed. A cluster patch in particular can take quite a while to apply if the machine…
Utilizing an array to gracefully append to a list of EmailAddresses
Learn how to find files with the shell using the find and locate commands. Use locate to find a needle in a haystack.: With locate, check if the file still exists.: Use find to get the actual location of the file.:
In a previous video, we went over how to export a DynamoDB table into Amazon S3.  In this video, we show how to load the export from S3 into a DynamoDB table.
Suggested Courses
Course of the Month18 days, 10 hours left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question