Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
440 views
in Technique[技术] by (71.8m points)

shell - Why is the output of my bash script not as expected?

I wanted to write a shell script (bash) in order to do the following:

The script is supposed to print all arguments passed when executing, that are (uneven **AND** greater than 66) **OR** (uneven **AND** less or equal than 88).

I wrote the following lines of code, hoping it would work as expected:

#!/bin/bash

param="$@"

for value in $param
do
  if [ $((value % 2)) -ne 0 ] && [ $((value)) -gt 66 ] || [ $((value)) -le 88 ]
  then
    echo "$value"
  fi
done

I do not get any errors, however, rather than filter the arguments looking for the mentioned criteria, the script prints any argument passed when executing. Should I add brackets to the if-statement or is there anything I'm overlooking?

Thanks in advance, I'm grateful for any advice :)

edit: I realize the problem is rather pointless, since the condition uneven number AND greater than 66 OR less or equal to 88 seems to include basically any odd number, no matter its size. I'm sorry for the confusion, I guess my prof just wanted us to practise writing shell scripts.

Thanks to @Ted Lyngmo for the advice.

#!/bin/bash

param=("$@")                # assign an array to param

for value in "${param[@]}"  # loop over the values in the array
do
  # use arithmetic expansion all the way for your condition:
  if (( (value % 2 != 0 && value > 66) || (value % 2 != 0 && value <= 88) ))
  then
    echo "$value"
  fi
done

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm assuming that you want (uneven numbers AND greater than 66) OR (even numbers that are less than or equal to 88) because of the comments made. That is, the ranges:

  • [-∞, 66], if even
  • [67, 88]
  • [89, +∞], if odd

Comments in the code:

#!/bin/bash

param=("$@")                # assign an array to param

for value in "${param[@]}"  # loop over the values in the array
do
  # use arithmetic expansion all the way for your condition:
  if (( (value % 2 != 0 && value > 66) || (value % 2 == 0 && value <= 88) ))
  then
    echo "$value"
  fi
done

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...