We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,610 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Problem with case in bash

Hello everyone,
i am fairly new to shell scripting so please bear with me.
The following script is supposed to read words from a file and depending on the word print different things.
However it always prints the default value.
It also refuses to work completely if the first line in 'numbers.txt' is not a blank line.

I would be grateful for any hints whatsoever.

script

#!/bin/bash

file="numbers.txt"

while read line 
do
operator=`awk '{print $1}' $line`
case $operator in
"divide") echo "/";;
"multiply") echo "x";;
"add") echo "+";;
"subtract") echo "-";;
*) echo "default";;
esac
done < "$file"

numbers.txt (the first line is a blank!)

divide
multiply
add
subtract
3
Contributors
5
Replies
5 Days
Discussion Span
3 Months Ago
Last Updated
11
Views
Question
Answered
replic
Junior Poster in Training
52 posts since Nov 2008
Reputation Points: 27
Solved Threads: 6
Skill Endorsements: 0

hi,

can you show the result of this command

cat -A numbers.txt
Watael
Junior Poster
121 posts since Apr 2012
Reputation Points: 4
Solved Threads: 26
Skill Endorsements: 2
$
divide$
multiply$
add$
subtract$
replic
Junior Poster in Training
52 posts since Nov 2008
Reputation Points: 27
Solved Threads: 6
Skill Endorsements: 0

You can solve the problem in much simpler steps by just combining the for loop with cat command results.

#!/bin/bash
filename="input.txt"
for word in `cat $filename`
do
        case $word in
                "divide") echo "/" ;;
                "multiply") echo "x" ;;
                "add") echo "+" ;;
                "subtract") echo "-" ;;
                *) echo "default" ;;
        esac
done
ravi89
Junior Poster
117 posts since Jun 2009
Reputation Points: 11
Solved Threads: 14
Skill Endorsements: 0

oops, my bad, I didn't see that line operator=$(awk '{print $1}' $line)it's bad, it should be operator=$(awk '{print $1}' <<< "$line")and useless!

simply use case $line in..., as numbers.txt has only one column.

Watael
Junior Poster
121 posts since Apr 2012
Reputation Points: 4
Solved Threads: 26
Skill Endorsements: 2

Thanks for the help.

replic
Junior Poster in Training
52 posts since Nov 2008
Reputation Points: 27
Solved Threads: 6
Skill Endorsements: 0
Question Answered as of 3 Months Ago by Watael and ravi89

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0695 seconds using 2.66MB