Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 576
Looking2learned Avatar asked Jun 12 '13 01:06

Looking2learned


People also ask

How do you sequence numbers in bash?

You can iterate the sequence of numbers in bash in two ways. One is by using the seq command, and another is by specifying the range in for loop. In the seq command, the sequence starts from one, the number increments by one in each step, and print each number in each line up to the upper limit by default.

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script.

What does $() mean in bash?

Dollar sign $ (Variable) The dollar sign before the thing in parenthesis usually refers to a variable. This means that this command is either passing an argument to that variable from a bash script or is getting the value of that variable for something.

What is $_ in bash?

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.


2 Answers

Use seq with the -s option:

seq -s, $counter -1 1 
like image 120
choroba Avatar answered Sep 30 '22 14:09

choroba


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
like image 35
Yang Avatar answered Sep 30 '22 14:09

Yang