0

I can't make this piece of code that uses single and double brackets work:

if [ ! $# == 1 ] && ! [[ $1 =~ ^[-]?[0-9]$ ]]; then exit 1 fi 

How can I mix both single and double types in the same expression? Thanks.

3
  • 3
    You probably meant if [ "$#" -ne 1 ] || ! [[ $1 =~ ^-?[0123456789]$ ]]; then exit 1; fi which can also be written if [[ $# -ne 1 || ! $1 =~ ^-?[0123456789]$ ]]; then exit 1; fi. Or in standard sh: case $#:$1 in (1:[0123456789] | 1:-[0123456789]) ;; (*) exit 1; esac Commented May 25, 2022 at 19:18
  • The expression works fine but there is no valid reason to mix these. Commented May 25, 2022 at 19:19
  • Way easier indeed @StéphaneChazelas!! I am still learning bash.. Thank you. That was very helpful! Commented May 25, 2022 at 19:21

1 Answer 1

1

Ok, with your help, I found a piece of code that works for my needs, no if needed. I used the following line:

[[ ! $# == 1 || ! $1 =~ ^-?[0-9]$ ]] && exit 1

Thank you all.

1
  • Beware [0-9] is not always the same as [0123456789] (can include a lot more characters that happen to also sort between 0 and 9 in some locales) so is best avoided for input validation. Commented May 25, 2022 at 19:53

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.