From 41d2b7258842fbb5e2f9f4242a96af97e33ee0ec Mon Sep 17 00:00:00 2001 From: Mingye Wang Date: Wed, 28 Oct 2015 01:11:46 -0400 Subject: [PATCH] Created SC2005 (markdown) --- SC2005.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 SC2005.md diff --git a/SC2005.md b/SC2005.md new file mode 100644 index 0000000..794e03a --- /dev/null +++ b/SC2005.md @@ -0,0 +1,27 @@ +Useless `echo`? Instead of `echo $(cmd)`, just use `cmd` +-------------------------------------------------------- + +### Problematic code: + +```sh +echo "$(cat 1.txt)" +echo `< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c6` +``` + +### Correct code: + +```sh +cat 1.txt # In bash, but faster and still sticks exactly one newline: printf '%s\n' "$(<1.txt)" +# The original `echo` sticks a newline; we want it too. +< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c6; echo +``` + +### Rationale + +The command substitution `$(foo)` yields the result of command `foo` with trailing newlines erased, and when it is passed to `echo` it generally just gives the same result as `foo`. + +### Exceptions + +One may want to use command substitutions plus `echo` to make sure there is exactly one trailing newline. The special command substitution `$(