简体   繁体   中英

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. 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. How do you do that?

You can use two shortcuts to do that ctrl + k and ctrl + 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:

echo "some command" && >

Now put \\ (backslash) and press enter :

echo "some command" && \
>

And now paste the part you've previously cut by 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 + f - move one word forwards (on 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). 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.

You can create text file for script. For example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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