INPUT_FILE=`ls -rt $MY_DIR/FILE.*.xml | head -1 | xargs basename`
I wanted to execute the second command (
head -1) only if the first command is successful. How do I improve this command?
Also, if you don't want the user to see any error output from
Also note that I added quotation marks around
If you're using a modern shell such as bash, you should use a
In a pipe line, all commands are started and run concurrently, not one after the other. So you need to store the output somewhere.
Note that it assumes file names don't contain newline characters. Using
To get the basename of the oldest file with
If there's no match, that command will fail and abort the script. You can also do:
In which case the
Find the latest modified file in a directory:
Instead of calling out to
In a directory with these contents:
The contents of the base_fn variable would be:
To use this properly to serve the purpose of your request:
EDIT: upon review of the question, i have realized that the
the important thing to note is that you absolutely, under no circumstances ever in mankind, should not parse the output of ls. never.
I think that the best option here is:
if there is no file then the return code of ls is 2 but if it finds some file will be 0.