tgun926
tgun926

Reputation: 1633

Bash if test breaks if at least one single quote in user input

If the user input contains a single quote such as in

$ echo "Hello my name Foo I'm 18" | ./test.sh

It fails with error syntax error: operand expected (error token is "'") Code:

#!/bin/sh
while read line
do
    str=$line
    for ((i = 0; i < ${#str}; i++))
    do
        if [[ "${str:$i:1}" -gt 4 ]]    <-- fails
        then
            echo 'foo'
        elif [[ "${str:$i:1}" -lt 4 ]]    <--- fails
        then
            echo 'bar'
        else
            echo 'not a number'
        fi
    done    
done

How can I make my code work when the user types in an apostrophe/single quote?

Upvotes: 1

Views: 57

Answers (1)

anubhava
anubhava

Reputation: 785541

You can use:

#!/bin/bash

while read -r line; do
    str=$line
    for ((i = 0; i < ${#str}; i++)); do
        ch="${str:$i:1}"
        if [[ $ch == [0-9] && $ch -gt 4 ]]; then
            echo 'foo'
        elif [[ $ch == [0-9] && $ch -lt 4 ]]; then
            echo 'bar'
        else
            echo 'not a number'
        fi
    done
done
  • Use /bin/bash instead of /bin/sh
  • Check if character is a digit using $ch == [0-9] before using -gt or -lt operators to avoid operand expected error.

Upvotes: 2

Related Questions