Tareq Ibrahim
Tareq Ibrahim

Reputation: 365

how to check for valid string input in bash?

code:

read location

accepted inputs are

"/home/(10 chars)" or "/(10 chars)" or "(10 chars)"

how to check for valid input? and how to cut the 10 chars from $location variable?

Upvotes: 1

Views: 2485

Answers (3)

Diego Torres Milano
Diego Torres Milano

Reputation: 69188

You need something like this:

case "$location" in
    /home/??????????)
        echo $location
        ;;

    /??????????)
        echo $location
        ;;

    ??????????)
        echo $location
        ;;

    *)
        d=$(dirname "$location")
        b=$(basename "$location")
        echo $d/${b:0:10}
esac

Upvotes: 2

dtyler
dtyler

Reputation: 1207

I would use a grep expression like so:

echo $location | grep -xq "\w\{10\}\|/\w\{10\}\|/home/\w\{10\}"

This matches lines which are exactly one of the following cases( caused by the -x ) and doesn't print the matching line (caused by the -q)

  • 10 characters
  • 10 characters with a leading /
  • 10 character preceded by '/home/'

To use this in a script, just drop it in an if statement like so:

if echo "$location" | grep -xq "\w\{10\}\|/\w\{10\}\|/home/\w\{10\}"; then
    # location valid
else
    # location not valid
fi

Upvotes: 1

Kilian Foth
Kilian Foth

Reputation: 14336

You want substitution operators. ${VAR#/home/} evaluates to the value of $VAR with a leading /home/ stripped, if it exists. By comparing the result of these expressions to $VAR itself you can determine whether your value matches, and what the stripped version is. And ${#VAR} gives you the length of a variable value.

Upvotes: 1

Related Questions