[英]How can I delete a specific variable from my PATH environment variable using fish shell
Given an input variable say usr/bin and the following PATH给定一个输入变量说 usr/bin 和以下路径
echo $PATH
/usr/local/bin /usr/bin /bin /usr/sbin /sbin /usr/local/sbin /Developer/bin
how can I write (in fish shell) a function that given the string/input can delete that path from my PATH variable?我如何编写(在鱼壳中)一个函数,该函数给出字符串/输入可以从我的 PATH 变量中删除该路径? ->Ideally one that deletes the first occurrence (vs one that deletes all occurrences of such variable)
-> 理想情况下删除第一个出现的变量(vs 删除所有出现的此类变量)
I was considering writing a small function such as我正在考虑编写一个小函数,例如
deleteFromPath usr/bin
Would it be better to write this in a scripting language like Perl/python/ruby rather than in fish shell?用像 Perl/python/ruby 这样的脚本语言而不是鱼壳来编写它会更好吗?
for x in $list
if [ $x = $argv ]
//delete element x from list -> How?
end
end
This is rather easy to do in fish.这在鱼中很容易做到。
With set -e
, you can erase not just entire variables, but also elements from lists, like set -e PATH[2]
to delete the second element (fish counts list indices from 1).使用
set -e
,您不仅可以删除整个变量,还可以删除列表中的元素,例如set -e PATH[2]
删除第二个元素(鱼从 1 开始计数列表索引)。
With contains -i
, you can find which index an element is at.使用
contains -i
,您可以找到元素所在的索引。
So you'll want to call set -e PATH[(contains -i $argv $PATH)]
.所以你需要调用
set -e PATH[(contains -i $argv $PATH)]
。
With some error-handling and edgecases fixed, this'd look like修复了一些错误处理和边缘情况后,这看起来像
function deleteFromPath
# This only uses the first argument
# if you want more, use a for-loop
# Or you might want to error `if set -q argv[2]`
# The "--" here is to protect from arguments or $PATH components that start with "-"
set -l index (contains -i -- $argv[1] $PATH)
# If the contains call fails, it returns nothing, so $index will have no elements
# (all variables in fish are lists)
if set -q index[1]
set -e PATH[$index]
else
return 1
end
end
Note that this compares the path strings , so you'd need to call deleteFromPath /usr/bin
, with the leading "/".请注意,这会比较路径字符串,因此您需要使用前导“/”调用
deleteFromPath /usr/bin
。 Otherwise it would not find the component.否则它不会找到该组件。
We can call through to bash.我们可以调用 bash。 :)
:)
function removePathElements
set PATH (bash -c 'IFS=: read -r -a path_entries <<<"$PATH"; for idx in "${!path_entries[@]}"; do for arg; do [[ ${path_entries[$idx]} = "$arg" ]] && unset path_entries[$idx]; done; done; printf "%s\n" "${path_entries[@]}"' _ $argv)
end
To be clear, the embedded bash code here is:需要明确的是,这里嵌入的 bash 代码是:
IFS=: read -r -a path_entries <<<"$PATH"
for idx in "${!path_entries[@]}"; do
for arg; do
[[ ${path_entries[$idx]} = "$arg" ]] && unset path_entries[$idx]
done
done
printf "%s\n" "${path_entries[@]}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.