1

Using ed put character # to the beginning of lines 10 to 20 in file /etc/passwd. Solution is the following

ed /etc/passwd <<\END
10,20s/^/#/
%p
Q
END

my question is that what does << means here and \ before END and why we use it. Do we have to use it all the time or not?

Kusalananda
  • 333,661
Somojel
  • 41

2 Answers2

4

What you are showing is ed being used together with an editing script.

The editing script (a series of ed commands) is being passed into ed as a here-document. A here-document is a piece of possibly multi-line text redirected into the standard input of a utility. The here-document is what's between the first and last END markers. The \ in front of the first END marker means that the document is quoted, meaning that the shell will not try to expand variables etc. in it. It could also have been written as <<'END'. In this specific instance, the \ can be removed since the editing script does not contain anything for the shell to expand.

This is a common way to use ed for simpler non-interactive editing, although ed should be used with its -s option when using it in this way.

The command is equivalent in effect to using sed with

sed '10,20/^/#/' /etc/passwd

(The ed script will make the changes in the file and then display the file in the terminal before exiting without saving the changes, which is more or less what the above sed script is doing on a line-by-line basis).


This is not a good way of editing the /etc/passwd file though (which the ed script is actually not doing, thankfully, since it doesn't save its changes). For that, tools like vipw or specific commands made for modifying this file (like useradd etc.) should be used. This is because the file, on many Unix systems, needs to be in sync with one or several other files or databases, and editing it requires updating these too (which e.g. vipw does automatically).

Kusalananda
  • 333,661
0

It's not ed, it's your shell.

It means take raw input until the word END and send it to the STDIN of a command.

For example:

$ cat <<\END
> something
> END
something

produces the same result as:

$ echo something | cat
something
  • The result may not always be the same depending on the use of quotes in the something string. Consider, for example the string "hello". – Kusalananda Apr 13 '18 at 17:59
  • It is the same if you quote/escape properly, which is half the reason to use the <<\END feature, so you don't have to worry about it. The shell is just passing the contents of the quotes to echo when you run echo "something", you could of course wrap it in singles to pass the double quotes to echo: echo '"something"' | cat or just escape the double quotes echo \"something\" | cat – rusty shackleford May 01 '18 at 10:13