8

I often find myself testing out a command (e.g. cat file | awk 'stuff') in the shell and when I'm satisfied with the way it works, I append the command to a script file.

Let's say this is the command I created cat file.txt | awk -F '|' '$3 == "\"0\""'

How can I quickly echo that to a file without having to escape stuff first and without having to use the mouse?

Is there a way to do something like

echo --verbatim the_command_with_lots_of_quotes_and_everything >> file.sh

or

cat <<'EOF'\n the_command \n EOF >> file.sh ?

Bloke
  • 231

1 Answers1

4

Not so quick, but zsh (and bash maybe?) has this feature called fc, I'm not sure what it stands for but if you type it, it seems to open up the command in whatever your $EDITOR is.

Or maybe you could do history | tail -1 >> file.

In terms of doing a heredoc in one line, this:

~$ echo -e "cat << EOF\nhello\n12345\nEOF\n" | sh
hello
12345

is the closest I can think of.

apricot boy
  • 1,153
  • 7
  • 11
  • this is slightly more clear to me: eval $'cat << DL > /home/user/test \nLine1\nLine2\nDL' (DL is the delimiter in a Heredoc cat << EOF > file.txt \nLine1\nLine2\nEOF https://linuxize.com/post/bash-heredoc/) $'..' is an ANSI C string https://unix.stackexchange.com/questions/48106/what-does-it-mean-to-have-a-dollarsign-prefixed-string-in-a-script "Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard." – alchemy Aug 01 '23 at 03:21