Bash – difference between read, head -1, and sed 1q

bashheadreadsedshell

The following commands seem to be roughly equivalent:

read varname
varname=$(head -1)
varname=$(sed 1q)

One difference is that read is a shell builtin while head and sed aren't.

Besides that, is there any difference in behavior between the three?

My motivation is to better understand the nuances of the shell and key utilities like head,sed. For example, if using head is an easy replacement for read, then why does read exist as a builtin?

Best Answer

Neither efficiency nor builtinness is the biggest difference. All of them will return different output for certain input.

  • head -n1 will provide a trailing newline only if the input has one.

  • sed 1q will always provide a trailing newline, but otherwise preserve the input.

  • read will never provide a trailing newline, and will interpret backslash sequences.

Additionally, read has additional options, such as splitting, timeouts, and input history, some of which are standard and others vary between shells.

Related Question