Reputation: 40773
I am a bash user trying zsh for the first time. In bash, I have functions to manipulate paths such as appending a directory to the path only if
For bash, I have something like:
# =============================================================================
# Returns true (0) if element is in the list, false (1) if not
# $1 = list, $2 = element
# =============================================================================
function lcontains() {
found=1 # 1=not found, 0=found
local IFS=:
for e in $1
do
if [[ $2 == $e ]]
then
found=0
break
fi
done
return $found
}
# =============================================================================
# Appends into a list an element
# $1 = list, $2 = element
# =============================================================================
function lappend() {
if [[ -d $2 ]] && ! lcontains "$1" "$2"
then
echo $1:$2
else
echo $1
fi
}
# Usage:
export PATH=$(lappend $PATH ~/bin)
# Add the same path again, and result in no duplication
export PATH=$(lappend $PATH ~/bin)
The trouble is, in zsh, the lcontains
function does not work because zsh does not split white space by default. So, is there a way to accomplish my objective?
Upvotes: 0
Views: 198
Reputation: 27758
General solution: split with IFS
.
function lcontains() {
local IFS=':'
local found=1 # 1=not found, 0=found
local e
for e in $(echo "$1")
do
if [[ $2 == $e ]]
then
found=0
break
fi
done
return $found
}
ZSH only solution: split by Parameter Expansion Flag s
function lcontains() {
local found=1 # 1=not found, 0=found
local e
for e in "${(@s#:#)1}"
do
if [[ $2 == $e ]]
then
found=0
break
fi
done
return $found
}
Upvotes: 1
Reputation: 22366
If you need splitting on space in zsh, you have to say this explicitly. For example, if
x="ab cd"
then $x
is passed as single parameter, but ${(z)x}
is passed as two parmeters, ab
and cd
.
Upvotes: 0