Home > database >  select an integer greater than 0 and less than 4 using bash
select an integer greater than 0 and less than 4 using bash

Time:10-12

I have written a bash script that allows a user to pick file names from an array by entering an index. This works fine except that I now need a function to validate numbers entered by the user. I tested the function using shellcheck which gave it the all clear.

#! /bin/bash
validateRange () {
if (( "$PICK" > "0" )) && (( "$PICK" <= "$LIMIT" )) then 
    echo "valid number"
fi
}
(( LIMIT=4 ))
(( PICK=2 ))
validateRange "$PICK" "$LIMIT"

shellcheck gave this the all clear

$ shellcheck myscript
No issues detected!

$

However the same code does not run in my .bash_functions script.

.bash_functions: line 201: syntax error near unexpected token `then'
.bash_functions: line 201: `  if (( "$PICK" > "0" )) && (( "$PICK" <= "$LIMIT" )) then '

I'm not sure what is wrong with my code. Is there another way to achieve this in bash ?

CodePudding user response:

A correct version of this script could be:

#!/bin/bash

validateRange () {
  if (( "$1" > 0 )) && (( "$1" <= "$2" ))
  then
    echo "valid number"
  fi
}

declare -i LIMIT
LIMIT=4
declare -i PICK
PICK=2
validateRange "$PICK" "$LIMIT"

CodePudding user response:

Try [ "$PICK" -gt 0 ]. There are quite a few other issues as well. I suggest you sit down and read through a Bash tutorial, the issues are very basic and obvious.

shellcheck is just a linter. It doesn't work if your syntax is already very wrong. You can use it together with https://github.com/bash-lsp/bash-language-server/.

  •  Tags:  
  • bash
  • Related