1169
Touch a file in Linux
(programming.dev)
Welcome to Programmer Humor!
This is a place where you can post jokes, memes, humor, etc. related to programming!
For sharing awful code theres also Programming Horror.
Is there a command that's actually just for creating a new file?
Nope. If you open a nonexistent path and you have permissions to write to that directory, then that file is created.
I guess printf "" > file
Feels dangerous to run. What happens if the file already exists and has something important in it?
touch -a
is probably betterThe other command could just be
printf '' >> file
to not overwrite it. Or even simpler>>file
and then interruptor
:>>file
then you don't need to interrupt.“:>>” is “append null” right? Do you get a file with a single ASCII NUL or is it truly empty?
Not really. I believe : is the "true" builtin. So it's like running a program that exits with zero and writes nothing to stdout. The >> streams the empty stdout into the named file.
$ :|wc -c 0 $ touch /tmp/f; :>>/tmp/f; wc -c /tmp/f 0 /tmp/f
that's awesome, did not know about that handy operator!
Yeah!
it's basically a noop, I use it as a placeholder when I'm writing a script, since bash doesn't accept code blocks with no commands
I mean,
nano filename
will work, but there's no mkfile that I can find...$>filename
would also work, but it's not explicitly for creating a new filemost shells will accept outputting from a silent command to a file, e.g.
:> foo.txt
(where:
is the posix synonym to thetrue
command)How often do you actually need a blank file though? Usually you'd be writing something in the file.
I'm betting that's why none ever materialized. Most tools that can manipulate a file, can also create that file first, so there's just never been a usecase.
Right-clicking the desktop to create a new txt file in Windows feels so natural, but I can't really think of any time you'd want to create a new file and do nothing with it in a CLI.
You might if some other program checks whether that file exists and behaves differently depending on that.
But even still, what's a realistic usecase that would that involve needing a blank, unmodified file in that instance?
One use case is if you're running a web server that is configured to return a "maintenance" page instead of the live site if a particular file exists. Which is actually pretty cool because then you don't have to update the config when you need to do something or let your users get a bunch of 502 errors, you just
touch maintenance
and you're good.That's a good one!