Subtract shellscript input argument value

Asked

Viewed 878 times

1

I have the script below that prints on the screen the even numbers of 1 until the input argument.

#!/bin/bash
for i in $(seq 1 ($1)); do
    if [ $(($i % 2)) -eq 0 ]
    then
    echo "$i \c"
    fi
done

For example, for the execution of the script with argument 10 the script prints the following

2 4 6 8 10 

I would like the script to print only up to the input value minus 1. That is, $1-1 which for this case is 9.


I have tried the following modification without success.

for i in $(seq 1 (( $1 - 1 )) ); do
    if [ $(($i % 2)) -eq 0 ]
    then
    echo "$i \c"
    fi
done

2 answers

1

I also got it this way

for i in $(seq 1  `expr $1 - 0`); do
    if [ $(($i % 2)) -eq 0 ]
    then
    echo "$i,\c"
    fi
done
  • To optimize more, you don’t even need to use the if, can directly apply the operator && (AND_IF), thus: [ $(($i % 2)) -eq 0 ] && echo "$i,\c"

1


You only need one $ in the subtraction expression (and remove spaces):

#!/bin/bash
for i in $(seq 1 $(($1 - 1))); do
  if [ $(($i % 2)) -eq 0 ]
  then
    echo "$i"
  fi
done

Extracting a variable becomes more readable:

#!/bin/bash
last=$(($1 - 1))
for i in $(seq 1 $last); do
  if [ $(($i % 2)) -eq 0 ]
  then
    echo "$i"
  fi
done

Like 1 will never be printed, not even the if it is necessary:

#!/bin/bash
last=$(($1 - 1))
for i in $(seq 2 2 $last); do echo $i; done

Several options! :)

  • Thanks! About 40 min after I posted the question I got. It was really the $ that was missing. As for the optimization of 1, I need it because that’s only part of the code. The rest will use odd ones.

  • That one seq Step 2 is pretty cool. I didn’t know you could do this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.