1

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?

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

please fix the grep solution to printf '%s' "$input" | tr $'\n' ' ' | grep -q -E '^...$'. i use tr $'\n' ' ' to replace every newline with an illegal character. here i assume that space is an illegal character. see also Check if a string matches a regex in Bash script
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.