Reputation: 365
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
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
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)
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
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