1

I am new to Shell Script programming. I am attempting to make a program that outputs only gives back the odd arguments. For example, "I am a robot" should give "I a" only.

I thought I could use the shift command to through the arguments along with while and if statements, but I am unsure of how to convey a division by 2 with a remainder of 1 in the square brackets in the if statement ([])

#!/bin/sh
X=$1
shift
while [ $# -gt 0 ]; do
  if [ "HELP HERE" ]; then
     X=$1
     echo $X
  fi
  shift
 done
echo $X

3 Answers 3

3

How about just shifting twice?

while [ $# -gt 0 ]; do
    X=$1
    echo $X
    shift
    shift
done
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot, that is a much better idea
This would be better written as shift 2.
@CharlesDuffy: That does not work. shift 2 won't shift anything if $# < 2, and therefore if an odd number of arguments is provided it will loop forever.
But by that token, won't you get an error from the second shift? The ksh I use on Linux gives an error message (ksh: nothing to shift) when I do shift on an empty argument list (or shift 2 on a one entry argument list). ... Answer: bash is more sensible and doesn't generate a message (but doesn't shift anything when you try to shift more items than there are to shift). So, differences between shells — what fun. I didn't expect the error from ksh; I expected shift 2 to shift 1 when there aren't two left. (/bin/sh on Solaris gives an error but does do the shift.) Weird!
0

nneonneo's idea must be better than the following, but I'm going to present a way that checks if the argument is odd just in case.

#!/bin/sh
cnt=1
while [ $# -gt 0 ]; do
  X=$1

  # output the current argument when the counter is odd.
  if [ $(($cnt%2)) -eq 1 ]; then
    echo $X
  fi

  cnt=$(($cnt+1))
  shift
done

Comments

0
#!/bin/bash

declare -a ODD
declare -a EVEN
ODDIX=0
EVENIX=0

while [ $# -ne 0 ]; do
    if (( $#%2 == 1 ));then
        ODD[$ODDIX]=$1
        ODDIX=$((ODDIX+1))
    else        
        EVEN[$EVENIX]=$1
        EVENIX=$((EVENIX+1))
    fi
    shift
done

echo ODD: ${ODD[@]}
echo EVEN: ${EVEN[@]}*

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.