0

I'm writing a script which will have some arguments and so I am using getopts but i want to solve the problem with one argument.

I use a switch, for example -d, and I want the argument for -d will be the path to a directory, like ./work.

I want to test the user's input for a string or path, not a number. Is there any solution to solve this problem? I want to solve it with something like:

If (test)
  then echo it is string
else 
  echo it is not string       
  • A number is a valid directory name. I would not do any such check. – John Kugelman Nov 12 '13 at 0:21
1

Every variable is a string.

If you want to distinguish “is a number” from “is not a number”, test that.

while getopts d: OPTLET; do
  case "$OPTLET" in
    d)
      case "$OPTARG" in
        *[!0-9]*) echo 1>&2 "Non-numeric argument to -d, stopping."; exit 2;;
        *) number_of_foo=$OPTARG;;
      esac;;
  esac
done

It isn't clear from your question whether this is what you really want. A number is a string. 123 is a valid file name. So if the argument to -d is supposed to be a potential file name, there is no validation to do. Any sequence of characters is a potentially valid file name.

  • The only caveats to the valid file name is that the slash character can only be used as a directory separator, not part of a file name, and NUL (aka \0) can't be part of any path or file name. Handling arbitrary paths is difficult. – l0b0 Nov 12 '13 at 10:51
  • @l0b0 Right, a pathname can contain any byte except NUL (including / at arbitrary positions) while a filename can contain any character except / and NUL. There are very few contexts where a command line argument would have to be a filename (sans directory) rather than a pathname. – Gilles Nov 12 '13 at 13:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.