Fish中实现Heredocs转Bash执行的缩写配置问题求助
在Fish中实现含here-doc内容的bash包裹执行缩写
问题场景
需要实现一个Fish缩写:当命令缓冲区存在<<时,自动将整个缓冲区内容用bash -c "<内容>"包裹执行。例如输入:
tee $HOME/Desktop/test << END I am testing! END
期望执行:
bash -c "tee $HOME/Desktop/test << END I am testing! END"
原实现代码运行报错fish: Expected a string, but found a redirection,原代码如下:
function run_in_bash # Run the command in bash bash -c "(commandline --current-buffer)" end abbr --add run_in_bash_abbr --regex '.*<<.*' --function run_in_bash
错误原因
Fish会优先解析commandline --current-buffer输出内容中的重定向符号<<,将其当作Fish自身的重定向操作,而非作为字符串参数传递给bash,因此触发语法错误。
解决方法
需要对缓冲区内容进行转义处理,避免Fish提前解析特殊符号,确保内容完整传递给bash。修改后的代码如下:
function run_in_bash set buffer_content (commandline --current-buffer) # 转义内容,保留换行并处理特殊字符 set escaped_content (string escape -n "$buffer_content") bash -c "$escaped_content" end abbr --add run_in_bash_abbr --regex '.*<<.*' --function run_in_bash
代码说明
commandline --current-buffer:获取当前命令缓冲区的完整内容string escape -n:对内容进行转义,保留换行符的同时,将重定向、引号等特殊字符转换为bash可识别的格式,避免Fish提前解析- 最终将转义后的内容作为参数传递给
bash -c,确保here-doc和其他特殊语法能在bash中正常执行
内容的提问来源于stack exchange,提问作者Ahmad Ismail
相关产品推荐
相关产品推荐

