你能把 fish shell 变量作为命令行参数吗?

Can you `split` fish shell variables as cmd line args

是否可以在 cmd 行参数中使用 fishshell 拆分变量?

假设我有一个变量 $args 设置如下:

$ set args "-a args"

现在,给出这个 python 程序 (test.py):

import sys
print(sys.argv)

如果我在 fishshell 中 运行 以上内容,我会得到以下输出:

$ python test.py $args
['test.py', '-a args']

注意参数是作为一个参数传递的。当我在 bash 中执行等效操作时,我得到以下输出:

$ python test.py $args
['test.py', '-a', 'params']

有没有办法让鱼的行为像bash?

您不希望鱼在变量扩展方面表现得像 bash(技术上任何 POSIX 兼容 shell)。 POSIX 行为是无穷无尽问题的根源,也是为什么您需要在几乎所有内容周围加上双引号的原因。事实上,大多数有经验的人都会告诉您在脚本顶部添加 IFS=$'\n' 以阻止自动拆分的发生。

一个答案是使用 fish 的 "every var is a list" 功能:set args "-a" "args"(引号只是为了清楚起见,在本例中不需要)。列表中的每个元素都成为命令的一个单独参数。即使 args 值包含空格,这也会做正确的事情。另一个答案是使用命令替换在空白处显式拆分字符串:a_cmd (string split ' ' $args)。如果 args 值包含空格,这将不会做正确的事情(在 fish 或 bash 中)。

我发现了一些鱼 commandline 标记化的小技巧:

function posix_expand_str --description "Expand a string the POSIX way."
  set __posix_expand_str__oldline (commandline)
  commandline $argv
  commandline -o
  commandline $__posix_expand_str__oldline
  set -e __posix_expand_str__oldline
end

所有字符串在测试期间似乎都是串联的。


当您意识到这回答了您的问题时,请接受。它只在您要求时使用 POSIX,并且 不会 断开字符串。 测试结果:

> posix_expand_str "hello world"
hello
world
> posix_expand_str "hello 'posix haters' world"
hello
posix haters
world
> posix_expand_str "hello" 'high rep "Whosebug staff"' "world"
hello
high
rep
Whosebug staff
world