From 8fbd163e15300ebf2df0789cf0a9c66b415c5ce1 Mon Sep 17 00:00:00 2001 From: Iain Patterson Date: Thu, 18 Feb 2010 10:44:46 +0000 Subject: [PATCH] Sanity check path rules with embedded variables. --- .profile.d/PATH.bashrc | 29 ++++++++++++++++++++++++----- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/.profile.d/PATH.bashrc b/.profile.d/PATH.bashrc index 0b82245..a67a5ba 100644 --- a/.profile.d/PATH.bashrc +++ b/.profile.d/PATH.bashrc @@ -49,16 +49,35 @@ function copypath() { [ -z "$path" ] || eval "export $newpath='$path'" } +# Try to expand variables in a path definition, discarding it if expansion fails. +function expandpath() { + local path="$1"; shift + + while [ -n "$path" ]; do + [ "${path/\$/}" = "$path" ] && return 0 + path="${path#*\$}" + + local var="${path%%/*}" + eval "[ -n \"\$$var\" ] || return 1" + done + + return 0 +} + # Helper. function addpath() { local path="$1"; shift local dir="$1"; shift - dir=$(eval echo "$dir") - if [ -d "$dir" ]; then - echo "$path:$dir" - else + if ! expandpath "$dir"; then echo "$path" + else + dir=$(eval echo "$dir") + if [ -d "$dir" ]; then + echo "$path:$dir" + else + echo "$path" + fi fi } @@ -129,4 +148,4 @@ for path in $PATHS; do done -unset DIR PATHS dir dirs path var source sanitisepath copypath makepath newpath addpath +unset DIR PATHS dir dirs path var source expandpath sanitisepath copypath makepath newpath addpath -- 2.20.1