Shell Pipe – How to Pipe Output of a Command if Successful

outputpipeshell

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?

Best Answer

Try this:

INPUT_FILE=`ls -rt "$MY_DIR"/FILE.*.xml | head -1 | xargs -r basename`

Passing xargs the -r flag will cause it to only run basename if reads at least one item from standard input (head -1).

head -1 will run but you won't see or capture any output from it.

Also, if you don't want the user to see any error output from ls, you can redirect ls's stderr stream to /dev/null.

INPUT_FILE=`ls -rt "$MY_DIR"/FILE.*.xml 2> /dev/null | head -1 | xargs -r basename`

Also note that I added quotation marks around $MY_DIR. That way, the command will not fail if $MY_DIR contains spaces.

If you're using a modern shell such as bash, you should use a $( ) capture shell instead of backticks. You should also consider changing the style of your variables. You should generally avoid using all-uppercase variable names in scripts. That style is generally reserved for reserved and environmental variables.

input_file=$(ls -rt "$my_dir"/FILE.*.xml 2> /dev/null | head -1 | xargs -r basename)
Related Question