PDA

View Full Version : [bash] Allowing for only absolute paths in script



altonbr
June 13th, 2008, 07:47 PM
I just ran into a problem where my script can only accept absolute paths. Since I don't have a blog, I thought I'd post my solution here:


if [ "`echo $1 | cut -d '/' -f 1`" != "" ]; then
echo 'Absolute paths only!
exit 1
fi

Examples:

$ echo './' | cut -d '/' -f 1 # local directory
.
$ echo '../' | cut -d '/' -f 1 # local directory, back one
..
$ echo 'var/' | cut -d '/' -f 1 # local directory
var
$ echo '/var' | cut -d '/' -f 1 # absolute directory (this is the only type of path that is accepted in the script above)

geirha
June 13th, 2008, 08:04 PM
You can do this with pure bash too.

[ "${1:0:1}" != "/" ] && echo "not an absolute path"

altonbr
June 13th, 2008, 08:11 PM
You can do this with pure bash too.

[ "${1:0:1}" != "/" ] && echo "not an absolute path"

What's "${1:0:1}" specifically do? Looks for variable $1, start at 0 and end after 1 character?

Phenax
June 13th, 2008, 08:19 PM
What's "${1:0:1}" specifically do? Looks for variable $1, start at 0 and end after 1 character?

Yep, pretty much makes sure the first character of the string is "/"

geirha
June 13th, 2008, 08:22 PM
What's "${1:0:1}" specifically do? Looks for variable $1, start at 0 and end after 1 character?

Exactly that.
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_10_03.html#sect_10_03_03_02

ghostdog74
June 14th, 2008, 01:19 AM
use case.


# path="/var"
# case $path in /* ) echo "yes";; esac
yes