简体   繁体   English

如何在命令行上已存在的 BASH 字符串中插入换行符

[英]how to insert newline in a already existing BASH string on the command line

Suppose I have typed and executed a long BASH command on the command line.假设我在命令行上输入并执行了一个长 BASH 命令。 Now I want to split it up.现在我想把它分开。 So with the history I have my long command again, but now I cannot give Enter to insert a newline.因此,根据历史记录,我再次拥有长命令,但现在我无法按 Enter 键插入换行符。 How do you do that?你是怎样做的?

You can use two shortcuts to do that ctrl + k and ctrl + y : 您可以使用两个快捷键来执行ctrl + kctrl + y

echo "some command" && echo "some other long command"

Now move cursor somewhere (in my example, cursor is marked by > ): 现在将光标移动到某处(在我的示例中,光标标记为> ):

echo "some command" && > echo "some other command"

Now press ctrl + k - this will cut everything after a cursor: 现在按ctrl + k - 这将删除光标后的所有内容:

echo "some command" && >

Now put \\ (backslash) and press enter : 现在放\\ (反斜杠)并按enter键:

echo "some command" && \
>

And now paste the part you've previously cut by ctrl + y : 现在粘贴你之前通过ctrl + y剪切的部分:

echo "some command" && \
echo "some other long command"

Edit : to move more easily around in a long command, you can use shortcuts: 编辑 :要在长命令中更容易移动,您可以使用快捷方式:

  • alt + b - move one word backwards (on Mac OS X: ESC + b ) alt + b - 向后移动一个单词(在Mac OS X上: ESC + b
  • alt + f - move one word forwards (on Mac OS X: ESC + f ) alt + f - 向前移动一个单词(在Mac OS X上: ESC + f

Ultra-solution 超解决方案

You can also open current line in a editor using Ctrl-x + Ctrl-e (two shortcuts, one after another). 您还可以使用Ctrl-x + Ctrl-e (两个快捷方式,一个接一个)在编辑器中打开当前行。 Then edit it just as a regular text file, save & quit and voila, edited command will execute. 然后将其编辑为常规文本文件,保存并退出,然后执行编辑的命令。

If you want to choose which editor to use, just set EDITOR environment variable. 如果要选择使用哪个编辑器,只需设置EDITOR环境变量即可。

You can create text file for script. 您可以为脚本创建文本文件。 For example: 例如:

test.sh test.sh

#!/bin/bash
echo Hello, world!

So you will need to execute this: 所以你需要执行这个:

chmod +x test.sh
./test.sh
b@localhost:/usr/src/linux-5.3.18-59.34-bib/net> echo -e "a
b
d
e"
a
b
d
e
b@localhost:/usr/src/linux-5.3.18-59.34-bib/net> echo -e "a
b\nc
d
e"
a
b
c
d
e

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM