Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 8013

General discussion • How to check if an argument is a valid file name?

$
0
0
Bash script on Linux:
I need to check if the supplied argument ($1) is an existing file (easy to do) or else is a file that can be created in an existing directory (how to do this?).
I am writing a logging script and I want to make sure that it has correct data for the logfile.
The logfile can be supplied on the command line as $1 or otherwise use a default in the script.

Code:

# Log file pathif [ -f "$1" ]; then # File exists so use supplied logfile  LOG_FILE="$1" else  if [ ??? ]; then # How can I check if $1 is a valid path for a file *to be created*?    LOG_FILE="$1"  fifiif [ "$LOG_FILE" == ""]; # Use default logfile  LOG_FILE="/etc/somedir/log/actions.log" #Default logfilefi
To be really sure that it will work when the LOG_FILE does not already exist, what can I do?
Maybe check if touch $LOG_FILE returns an error?
For instance if the supplied filename points to a non-existing dir then what?

Statistics: Posted by Bosse_B — Mon Feb 26, 2024 6:58 am



Viewing all articles
Browse latest Browse all 8013

Trending Articles