在Fish Shell中如何在字符串中换行?

8
这是与以下问题相同的问题:如何在fish shell中将字符串换行? 在bash中,我们有: $'this is line\nthis is another line' 它会产生预期的结果,但在fish shell中却无法运行。
Fish有一种类似的方法吗? 编辑1: 像faho明智地提到的那样,有文字方法: 'this is line this is another line' 但我真的很好奇是否存在一种方法可以将\n作为换行符而不是文字,就像在shell中一样。
我想知道是否可以使用这个字符串"this is a line\nthis is another line",确保fish将\n视为换行符而不是文字。

1
有趣的是,fish设计文档将$''描述为“愚蠢的”。(链接:https://fishshell.com/docs/current/design.html#ortho) - glenn jackman
1
非常感谢。有趣的是,现在我明白了fish shell对此的立场。 - Iury Fukuda
3个回答

7
  1. Fish将引号外的\n替换为换行符,所以您可以停止并重新开始引号(注意引号前面没有“$”):

'this is line'\n'this is another line'

  1. Fish跨行跟踪引号,因此您可以包含一个文字换行符:

'this is line this is another line'


谢谢您花时间回答我的问题。我也可以在Shell中使用这种方法。还有另一种方法可以保留类似于Shell中的“\n”的格式吗? - Iury Fukuda
不行,在“shell”中你不能这样做。类 POSIX 的 shell 不会解释 $'' 之外的 \n - echo 'a'\n'b' 会打印出 anb - faho
在 fish 和 POSIX shell 中,也有 echo -e 命令,它会解析字符串中的反斜杠转义符号,所以 echo -e 'a\nb' 会打印 a、一个换行符和 b。我建议你使用我提供的第一种方式,因为它不受传递参数的影响,始终可用。 - faho

4
您可以使用echo -e命令(启用反斜杠转义解释),正如@faho在评论中所指出的那样。
$ echo -e "## Foo\nBar"
## Foo
Bar

来自 man echo

Escape sequences

   If -e is used, the following sequences are recognized:

   o \ backslash

   o \a alert (BEL)

   o \b backspace

   o \c produce no further output

   o \e escape

   o \f form feed

   o \n new line

   o \r carriage return

   o \t horizontal tab

   o \v vertical tab

   o \0NNN byte with octal value NNN (1 to 3 digits)

   o \xHH byte with hexadecimal value HH (1 to 2 digits)

-2

编辑你的config.fish文件。
在Ubuntu中的示例:sudo nano /etc/fish/config.fish
提示函数控制fish终端的外观。粘贴以下代码:

# 将系统范围的fish配置条目放在这里
# 或者在conf.d/中的.fish文件中
# conf.d中的文件可以被用户覆盖
# 通过与$XDG_CONFIG_HOME/fish/conf.d中相同名称的文件
# 所有fish实例都会运行此文件。 # 要仅包括登录shell的配置,请使用 # if status --is-login # ... # end # 要仅包括交互式shell的配置,请使用 # if status --is-interactive # ... # end #
function fish_prompt -d "编写提示" # 更改输出颜色 set -U fish_color_command '2cff8f' -o
# 别名 alias cls='clear'
# 提示符 printf '%s@%s%s%s%s\n@>' (whoami) (hostname | cut -d . -f 1) \ (set_color $fish_color_cwd) (prompt_pwd) (set_color normal) end

我猜重点是执行 printf '第一行\n第二行' - Dorian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接