0

How would I write a Linux script to print numbers 1 through n, one on each line. But if n isn't specified, a default value of 10 will be used.

Example: script name is value

./value 20 should print 1 through 20 on each line

./value should print 1 through 10 on each line by default

My Script:

#!/bin/bash

num=$1
for (( i = 1 ; i <= ${num} ; i++ ))
do   
  echo $i
done
codeforester
  • 39,467
  • 16
  • 112
  • 140
J Pham
  • 3
  • 1

3 Answers3

1

Put in the rest of the substitution.

${num:-10}
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

Check the following:

#!/bin/bash

num=${1:-10}

for (( i = 1 ; i <= ${num} ; i++ ))

do

echo $i

done
hirakJS
  • 109
  • 5
0

You can simply catch an empty argument and replace it, with something like:

num=$1
[[ -z "$num" ]] && num=10

The advantage to this method is that you can apply arbitrary checks to the argument to ensure it's valid, not just catching an empty argument:

deflt=10
[[ -z "$num" ]]        && echo 'No argument'     && num=$deflt
[[ $num =~ -.* ]]      && echo 'Starts with "-"' && num=$deflt
[[ ! $num =~ [0-9]+ ]] && echo 'Not integer'     && num=$deflt
[[ $num -gt 99 ]]      && echo 'Too big'         && num=$deflt
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953