I want to check if a shell variable contains an absolute path.
I don't care if the path exists or not—if it doesn't I'm going to create it—but I do want to ensure that I'm dealing with an absolute pathname.
My code looks something like the following:
myfunction() {
[ magic test to see if "$1" is an absolute path ] || return 1
mkdir -p "$(dirname "$1")" || return 1
commands >> "$1"
}
Or, the use case where the absolute path to be verified is intended to be a directory:
anotherfunction() {
[ same magic test ] || return 1
mkdir -p "$1"
dostuff >> "$1/somefile"
}
If this were awk
I would do the check like so: myvar ~ /^\//
There must be a clean way to do this with the shell's string handling, but I'm having trouble coming up with it.
(Mentioning a bash
-specific solution would be fine but I'd like to know how to do this portably, also. POSIX string handling seems like it should be sufficient for this.)
pathchk
command. Perfect. I'll leave open for a while longer to see if anything better shows up, but I think you nailed it—case
switch plus a command actually designed to check a pathname. :) – Wildcard Jan 20 '16 at 01:34-pP
can also be used to single out paths with weird characters and other riffraff. – mikeserv Jan 20 '16 at 01:41-
dash, huh...? – mikeserv Jan 20 '16 at 02:54-P
seems to be useless here, since when any path like/path/to/-_start_with_dash
is fine. – cuonglm Jan 20 '16 at 03:12pathchk -Pp
. And you can dofn(){ pathchk -P "$@"; }
to get a list of the arguments that start w/ - printed to stderr. – mikeserv Jan 20 '16 at 03:14-P
for empty path. – cuonglm Jan 20 '16 at 03:16[ ${1:+"!"} "${1%%/*}" ]
– mikeserv Jan 20 '16 at 03:18...in (/*) pathchk...
and not...in /*) pathchk...
, and is it possible to access the current element anyhow inside the "case" blocks? – Artfaith Jan 30 '24 at 12:43