Looking2learned
Looking2learned

Reputation: 213

Generating a comma-separated sequence of numbers based on input in Bash

I've found more than few things on here to help me as I'm learning to code in Bash and they all come close but not quite.

I need to take an input of a positive integer and print out on a single line down to one, all separated by commas, without a comma at the end of the last variable.

This is what I have so far:

#!/bin/bash
#countdown

read -p "Enter a Number great than 1: " counter

until ((counter < 1)); do
echo -n ",$counter"
((counter--))
done

It almost works out but I can't figure out how to prevent the comma in front and not have it behind the last variable.

EDIT: You guys are AMAZING. Poured over this book and learned more in ten minutes here than I did with an hour there.

So is there some sort of command I could use to ensure it was only one number entered and ensure it had to be positive?

Some way to put an if statement on the read to ensure its <= 1 and only one character?

I only have a background in some basic C coding, so I have the basics but translating them to BASH is harder than expected

Upvotes: 6

Views: 11146

Answers (5)

jaypal singh
jaypal singh

Reputation: 77105

Here is another way … kinda influenced by chepner's solution but not using seq:

Content of script.sh:

#!/bin/bash

read -p "Enter a Number great than 1: " counter
range=( $(eval echo {$counter..1}) )
( IFS=,; echo "${range[*]}" )

Test:

$ bash script.sh
Enter a Number great than 1: 5
5,4,3,2,1
$ bash script.sh
Enter a Number great than 1: 30
30,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1

Upvotes: 1

Yang
Yang

Reputation: 8170

Probably simper way using brace expansion:

#!/bin/bash
#countdown

read -p "Enter a Number great than 1: " counter

eval printf "%s" {${counter}..2}, 1

Test:

Enter a Number great than 1: 10
10,9,8,7,6,5,4,3,2,1

To validate the input, you can use regular expressions:

#!/bin/bash
#countdown

read -p "Enter a Number great than 1: " counter

if [[ ${counter} =~ ^[1-9][0-9]*$ ]]
then
  eval printf "%s" {${counter}..2}, 1
fi

Upvotes: 6

chepner
chepner

Reputation: 531165

A slightly awkward construction using an array, the seq command, and a subshell to localize a change to the IFS parameter will work.

read -p "Enter a Number great than 1: " counter
range=( $(seq $counter -1 1) )
( IFS=,; echo "${range[*]}" )

Upvotes: 1

choroba
choroba

Reputation: 241878

Use seq with the -s option:

seq -s, $counter -1 1 

Upvotes: 16

jim mcnamara
jim mcnamara

Reputation: 16379

One way

read -p "Enter a Number great than 1: " counter
echo -n "$counter"
((counter--))
until ((counter < 1)); do
echo -n ",$counter"
((counter--))
done

Upvotes: 2

Related Questions