Is there a programmatic way to find out why I can't write to a file in a shell script (file exists, access denied, filesystem full, etc)?
For example in C one uses the errno
variable for this:
FILE *fp = fopen("/etc/passwd", "w");
if (!fp) {
if (errno == EACCES) {
// ...
}
else if (errno == EEXISTS) {
// ...
}
}
Can I do something similar with shell scripting?
My test script:
#!/bin/sh
err=$(echo 'x' 2>&1 > /etc/passwd)
if [ $? -ne 0 ]; then
echo "An error occured: $err"
exit 1
fi
Running this, as a non-root user, will give you:
An error occured: 'test.sh: line 3: /etc/passwd: Permission denied'
Checking the contents of $err
is not a very good solution IMHO; the error message may change in the future, and is dependent on the user's locale
settings.
I also know I can do a stat
& some other checks before creating a file, or after the exit code is non-zero; but this quickly gets out of hand if you want to check all possible errors. In some cases, it's also susceptible to race conditions (such as the file being creating between your test -f
and actually writing it).
I'm using the POSIX shell, and would prefer to do it in a POSIX-compliant way, but a bash
or zsh
extension is also acceptable.
$?
is the exit/error code. that's about all you'll get other than the actual string output you're capturing.