When creating a new directory using the mkdir
command, I can simply add the -v option to find out whether or not the new directory is created. It saves time on not issuing a ls -F
command. Is there any way to ensure that a new file was created using the touch
command? Or should I use another command instead of touch
?

- 85
1 Answers
That's what the exit status is for.
touch
is the command to update the time stamps of a file or create it if it the file didn't exist in the first place.
It will return success in its exit status if it fulfilled that goal, and failure otherwise¹. If it failed, it will generally output an error message about it to detail in which way it failed.
if touch -- "$file"; then
printf '%s\n' "$file was created or updated"
fi
In your script, if you want to make sure you don't carry on if touch
did not succeed, you'd write it:
touch -- "$file" || exit
(here the script would exit with the same failure exit status as that reported by touch
).
Or add a else exit
in the if
statement above.
¹ touch
could also report failure even though it managed to update the file in some pathological cases, like it was killed or ran out of some resource. In most of those cases, it's probably just as well for your script to consider it a failure to update the file

- 544,893
touch
command", do you mean "was created exactly by thistouch
command"? as opposed to a file that already existed? I'm asking becausels -F
cannot tell you if the previousmkdir -v
actually created a directory or found it existing; but the output ofmkdir -v
is different in the two cases. So it's not clear if you want to ensure that "dir/file gets created exactly by the command" or "it exists after the command". – Kamil Maciorowski Jul 25 '20 at 06:13--verbose
option in the man page fortouch
that does that for me. – Dsaki Jul 25 '20 at 06:20mkdir
/touch
exiting silently means there were no problems. If there were problems the tool knew of, then it would print an error message. If there were problems the tool didn't know of (artificial example: an insane filesystem pretends all actions are successful but no file gets created ever), then no option would make the difference (unless the option was to verify independently). What's wrong in seeing no error message? I think the rationale behindmkdir -v
is not to ensure; it's to get a list you can parse. To ensure, "no error" should be OK. – Kamil Maciorowski Jul 25 '20 at 06:40touch
exits silently, this means that it worked. Themkdir -v
rationale was also a good point. – Dsaki Jul 25 '20 at 06:48