Subtract shellscript input argument value

1

I have the script below that prints on the screen the even numbers from 1 to 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, to script 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 value of the entry 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
    
asked by anonymous 20.06.2017 / 06:25

2 answers

1

You only need a $ 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

As 1 will never be printed, not even if is required:

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

Multiple options! :)

    
20.06.2017 / 12:05
1

I also managed this way

for i in $(seq 1  'expr $1 - 0'); do
    if [ $(($i % 2)) -eq 0 ]
    then
    echo "$i,\c"
    fi
done
    
20.06.2017 / 19:08