I have a bash program that will write to an output file. This file may or may not exist, but the script must check permissions and fail early. I can't find an elegant way to make this happen. Here's what I have tried.
set +e touch $file set -e if [ $? -ne 0 ]; then exit;fi
I keep set -e
on for this script so it fails if there is ever an error on any line. Is there an easier way to do the above script?
In order to check if a file does not exist using Bash, you have to use the “!” symbol followed by the “-f” option and the file that you want to check. Similarly, you can use shorter forms if you want to quickly check if a file does not exist directly in your terminal.
If you don't care about the mtime, you could use >>/Scripts/file. txt . This will open the file for appending and create it if it doesn't exist.
To check if the a file is readable, in other words if the file has read permissions, using bash scripting, use [ -r FILE ] expression with bash if statement.
Create File with cat Command The cat command is short for concatenate. It can be used to output the contents of several files, one file, or even part of a file. If the file doesn't exist, the Linux cat command will create it.
Why complicate things?
file=exists_and_writeable if [ ! -e "$file" ] ; then touch "$file" fi if [ ! -w "$file" ] ; then echo cannot write to $file exit 1 fi
Or, more concisely,
( [ -e "$file" ] || touch "$file" ) && [ ! -w "$file" ] && echo cannot write to $file && exit 1
Rather than check $?
on a different line, check the return value immediately like this:
touch file || exit
As long as your umask
doesn't restrict the write bit from being set, you can just rely on the return value of touch
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With