1,105,328 Community Members

Problem with case in bash

Member Avatar
replic
Junior Poster in Training
52 posts since Nov 2008
Reputation Points: 17 [?]
Q&As Helped to Solve: 6 [?]
Skill Endorsements: 0 [?]
 
0
 

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
Member Avatar
Watael
Junior Poster
134 posts since Apr 2012
Reputation Points: 4 [?]
Q&As Helped to Solve: 27 [?]
Skill Endorsements: 2 [?]
 
0
 

hi,

can you show the result of this command

cat -A numbers.txt
Member Avatar
replic
Junior Poster in Training
52 posts since Nov 2008
Reputation Points: 17 [?]
Q&As Helped to Solve: 6 [?]
Skill Endorsements: 0 [?]
 
0
 
$
divide$
multiply$
add$
subtract$
Member Avatar
b1izzard
Junior Poster
118 posts since Jun 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 14 [?]
Skill Endorsements: 0 [?]
 
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
Member Avatar
Watael
Junior Poster
134 posts since Apr 2012
Reputation Points: 4 [?]
Q&As Helped to Solve: 27 [?]
Skill Endorsements: 2 [?]
 
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.

Member Avatar
replic
Junior Poster in Training
52 posts since Nov 2008
Reputation Points: 17 [?]
Q&As Helped to Solve: 6 [?]
Skill Endorsements: 0 [?]
 
0
 

Thanks for the help.

Question Answered as of 1 Year Ago by Watael and b1izzard
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: