I’m inexperienced with bash
scripts, mostly cobbling things together from google searches. The following simple script creates file foo and changes its permission bits to whatever the script’s $1
is. Can an experienced bash
scripter please advise what would be a proper and/or efficient way to ensure that $1
is valid permission bits, i.e. a valid arg1
to chmod
?
#!/bin/sh #mkfoo.sh if [ $# -eq 0 ] then return fi perm=$1 touch ./foo chmod "${perm}" ./foo
As part of my inexperience, I’m unclear when/why variables are strings or integers. A string-validation approach feels infeasible because of the number of values the permission bits could be. What comes to mind is that I’d want to validate whether $1
is an integer, and if so, that it’s between 0 and 777. But I’m unclear if that’s a sufficient/efficient validation: I’ve got a rudimentary understanding of linux file permissions, and I’m led to believe there are lots of subtleties. Grateful for help.
Advertisement
Answer
From your comments, your goal is to give up on the chmod if the permissions specified are invalid.
chmod "$1" ./foo 2>/dev/null
2
is the file descriptor for stderr. Redirecting to /dev/null
will let it fail silently. chmod
, as stated in the comments, does its own validation on if the permissions are acceptable.