Check if shell variable contains an absolute path
6
votes
8
answers
14700
views
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.)
Asked by Wildcard
(37446 rep)
Jan 20, 2016, 12:57 AM
Last activity: Jul 20, 2025, 07:52 AM
Last activity: Jul 20, 2025, 07:52 AM