News for hackers. Stuff that matters.
Re:How to write idempotent Bash scripts by zokier on Sunday July 07, 2019 @11:32AM (#20375587)
The first example ("idiom") is bit tricky, because the title is "Creating an empty file". An alternative would for example be

    echo -n > example.txt
Both fit the description of "Creating an empty file". Is it idempotent, or more or less so than `touch example.txt`? If there is already an existing file, then touching it obviously will not empty it, so the end state is not "empty file exists" like one would expect from operation "Creating an empty file"

Ironically article calls "This is an easy one"

Re:How to write idempotent Bash scripts by gabrielblack on Sunday July 07, 2019 @02:47PM (#20376927)
"echo -n " is useless, is sufficient:

> example.txt

without prepending the echo command. This will create an empty file or it will truncate an existent file. The touch command could be preferable to preserve the content, if needed.

Re:How to write idempotent Bash scripts by gabrielblack on Monday July 08, 2019 @03:39AM (#20380697)
P.S.

>> example.txt

this one (with a double > ) could replace touch in this application case: it's less readable but more efficient.

Re:How to write idempotent Bash scripts by dylan604 on Sunday July 07, 2019 @12:45PM (#20376005)
If a file has a line ending in it, is it truly empty?
Re:How to write idempotent Bash scripts by fwip on Sunday July 07, 2019 @01:08PM (#20376186)
The -n flag keeps echo from emitting a line ending.
Re:How to write idempotent Bash scripts by dylan604 on Sunday July 07, 2019 @01:26PM (#20376294)
doh! I read it as \n, but then that's for other languages, so i was just all sorts of not paying attention
Re:How to write idempotent Bash scripts by mappu on Monday July 08, 2019 @03:32AM (#20380664)
I used a distro in recent memory where `echo -n foo` really produced `-n foo`.

The workaround was `printf "%s" foo`.

Re:How to write idempotent Bash scripts by fwip on Monday July 08, 2019 @11:40AM (#20383655)
Ah yeah, posix doesn't require -n to do anything in particular. For most use cases, strict adherence to posix compatibility isn't important, but sometimes it really really is.