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

Why complicate things?

file=exists_and_writeable

if ! [ -e "$file" ] ; then
    touch "$file"
fi

if ! [ -w "$file" ] ; then
    printf 'cannot write to %s\n' "$file"
    exit 1
fi

Or, more concisely,

{ [ -e "$file" ] || touch "$file"; } && \
    ! [ -w "$file" ] && printf 'cannot write to %s' "$file" && exit 1

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)