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?

Tareq Ibrahim
  • 365
  • 5
  • 18

3 Answers3

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
Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134
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.

Kilian Foth
  • 13,904
  • 5
  • 39
  • 57
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
dtyler
  • 1,187
  • 6
  • 11
  • 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](https://stackoverflow.com/questions/21112707/check-if-a-string-matches-a-regex-in-bash-script) – milahu Jul 09 '22 at 07:39