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.
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.
[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.
if [ "$#" -ne 1 ] || ! [[ $1 =~ ^-?[0123456789]$ ]]; then exit 1; fiwhich can also be writtenif [[ $# -ne 1 || ! $1 =~ ^-?[0123456789]$ ]]; then exit 1; fi. Or in standard sh:case $#:$1 in (1:[0123456789] | 1:-[0123456789]) ;; (*) exit 1; esac