How to check the user input to be valid using shell script?

How to check the user input to be valid using shell script?

The valid input is in the format like as follows.

  1. It can only have r,w,x or a hyphen and nothing else.
  2. ensure the r, w, x are in the correct order.

for example: rwxr-xr-x is a valid format.

Thanks

First, your input (obviously a filemode mask) has more structure: the "r" can only appear in the 1nd, 4th or 7th place, the "w" can only appear in the 2rd, 5th or 8th place, etc.

Construct a regular expression for this and compare the input string against this regexp:

typeset input=""

print - "Enter input string: " ; read input
if print - "$input" | grep -q '^[-r][-w][-x][-r][-w][-x][-r][-w][-x]$' ; then
     print - "input: $input \tstatus: OK"
else
     print - "input: $input \tstatus: Not OK"
fi

I hope this helps.

bakunin

1 Like

If we're being picky (and I do love to be picky), you should add the sticky, setuid, and setgid flags too.
Resulting in:
^[-r][-w][-xXs][-r][-w][-xXs][-r][-w][-xXt]$
(The capital letter X is where you've got a forth byte set but no execute).

1 Like

Thank you 2.
I got your idea although I can not run your code due to compile error.
Is there any convenient command to convert or substitute "rwxr-xr-x" to be "111101101"?
That means "change "r","w","x" to be "1", "-" to be "0".
After that, I want to change binary to octal format by "bc"? Is it a good method by "bc"?
I am a beginner. thanks for help.

What do you mean by "compile error"? What i wrote was Korn-Shell code. Which programming language are you using? (If not a shell, you are probably in the wrong forum. Say so and i transfer the thread to where it belongs.)

I hope this helps.

bakunin

Hi bakunin,

I am a beginner and only use bash shell. I got your idea and changed it to bash shell. It works. Thank you very much.