How do I paste multi-line bash codes into terminal and run it all at once?

Viewed 139777

I need to paste a multi-line bash code into terminal, but whenever I do, each line gets run as a separate command as soon as it gets pasted.

13 Answers

Another possibility:

bash << EOF
echo "Hello"
echo "World"
EOF

iTerm handles multiple-line command perfectly, it saves multiple-lines command as one command, then we can use Cmd+ Shift + ; to navigate the history.

Check more iTerm tips at Working effectively with iTerm

I'm surprised no one's said this, but you can use fc to paste all the commands in an editor and run them at once

Try this way:

echo $( 
    cmd1
    cmd2
    ...
)

So I think for very long command (namely compiling a file with llvm!) this has given me the most ease of us over the others Ive tried in the past. I use it all the time to thrash out a command in an editor over multiple lines:

cat | paste -sd " "  - | xargs echo

This will open up cat standard input in the terminal, paste in the code and follow up with ctrl-d (mentioned before this adds a EOF char and ends CAT process). Paste takes in the cat input and scoops up all multi lines into a space char. This will ONLY echo out the command.

To execute the command just add sh to the end:

cat | paste -sd " "  - | xargs echo | sh

Or alternatively I like to make the output an alias command, place in .zshrc

alias mcmd='cat | paste -sd " "  - | xargs echo'

then to execute

> mcmd | sh

this will open cat, paste in your multi line command, ctrl d and will execute the multi lines as a one line command :)

Example command

>    mcmd;
# now paste in your long command
> llvm-g++
    main.mm
    -o
    buildApp
    -w
    -g
    -std=c++14
    -L/System/Library/Frameworks/
    -framework
    CoreServices
     # now key press ctrl + d

whoop! outputs single line

 llvm-g++ main.mm -o buildApp -w -g -std=c++14 -L/System/Library/Frameworks/ -framework CoreServices

I have vi key bindings set in my shell. I don't recall, offhand, how I configured this. But when entering a command, I can switch from editing into command mode, type v and have the command automatically pop up in a vim session. Exiting the session (:wq) submits the command to bash for execution.

Related