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 ?

3
  • set -v; { # commands\n} 2>>file; set -; or fc -nl -0
    – mikeserv
    Jan 20, 2016 at 14:10
  • Do you want to store the command only or also the output by command?
    – Pandya
    Jan 20, 2016 at 14:11
  • cat >> file.sh; (type command here); (type control-D here)
    – Jeff Schaller
    Jan 20, 2016 at 14:14

1 Answer 1

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.

1
  • 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 linuxize.com/post/bash-heredoc) $'..' is an ANSI C string unix.stackexchange.com/questions/48106/… "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 1, 2023 at 3:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .