Added condition testing docs

This commit is contained in:
Ezri Brimhall 2024-10-01 18:51:02 -06:00
parent d211e95db4
commit e3e7d5b226
Signed by: ezri
GPG Key ID: 3DA1675C4E9B9216

View File

@ -0,0 +1,13 @@
## Testing a Condition
There are a number of ways to test conditions like this. My go-to is generally as follows:
`[ -s /path/to/some/test/file ] && echo "condition was true" || echo "condition was false"`
It is worth pointing out that it is possible to use `if` statements from the command line, just as you can in a script. It is definitely more cumbersome though.
One thing to look out for is quoting issues with an unquoted shell variable. It might be prudent to wrap that in quotes (so `"$FILE"`) so as to avoid these issues. As such, I'd also test by setting the variable `FILE` in my shell and running the conditional as-written in the script (rather than substituting a test file path directly) if using a test file directly didn't show any issues.
If that still doesn't work as expected, I'd start looking at the output of the `ls` command on the test file(s). Specifically, I'd be using `ls -lh`. Since this condition is checking for the existence and non-zero size of the given file, I want to make sure that the input data is what I'm expecting.
If the files exist but are empty, and this is expected (for example, they exist as flags created with `touch`), I'd probably change to a different condition (e.g. `-f` or `-e`), but ultimately anything beyond the above conditional statement would be more situation-dependent, and I don't currently have enough information on the nature of the problem this conditional is being used to solve to give a more specific example.