Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: Create a file if it does not exist, otherwise check to see if it is writeable

Tags:

linux

bash

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?

like image 201
User1 Avatar asked Dec 22 '10 16:12

User1


People also ask

How do you test if a file does not exist in bash?

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.

How do you create a file if it doesn't exist in shell script?

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.

How do you check if a file exists and is readable in bash?

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.

What command will create a file that does not exist?

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.


2 Answers

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 
like image 87
sorpigal Avatar answered Sep 25 '22 09:09

sorpigal


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

like image 31
SiegeX Avatar answered Sep 23 '22 09:09

SiegeX