Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell Programming with Modulus Operation

Tags:

shell

modulus

I'm trying to write a shell program that, given an argument, prints the name of the program and every odd word in the argument (that is, not even words). However, I am not getting the expected result. Upon tracing my program, I notice that, despite modulus returning values of 1 on odd words (say, the 5th word, 5 % 2 = 1), the program still treats the result as 0 (an even word) and doesn't print the word. What might be going wrong here?

Included here is my code and the traced output to see exactly what I am getting. (Sorry for not including the code as text, I'm new to vim and don't know copy/paste yet) Code Output


2 Answers

$result (needs a dollar sign )

like image 93
jspcal Avatar answered Jul 18 '26 13:07

jspcal


Change echo \$$# to echo $1. But it would probably be simpler to re-write the script:

#!/bin/sh

echo $0
while [ $# -gt 0 ]; do
    expr $# % 2 > /dev/null && echo $1
    shift
done
like image 42
William Pursell Avatar answered Jul 18 '26 12:07

William Pursell