MAK MAK - 2 years ago 88
Bash Question

Unix Shell Script: Display custom message if given extension file not exists in directory

I have the following unix shell script, which is used to list the files in the given directory. Only we need to pass the extension of the file and script should list the file or files or display custom message.

My try:



FileNameWithPath=`ls home\docs\customers\*.$1 | wc -w`

if [ $FileNameWithPath -gt 0 ]
ls home\docs\customes\*.$1
echo "Custom Message about failure(File not found)"


$ ./ txt

Note: The above script works fine if i give file extension which is exists but if i give some non exists file extension it will through error plus custom error message. I just want to print custom message that's it.

Answer Source

You can do it with a single command:

ls home/docs/customers/*.$1 2> /dev/null || echo "Custom message about failure (File not found)"

The first command (the 'ls') try to list the files. If it fails, it will print an error message (suppressed by '2> /dev/null') and returns an error code. Since the exit code is different by 0, the second part (the 'echo') will be executed.

If you want to keep your code, you can drop the ls error redirecting stderr to /dev/null in this way:

FileNameWithPath=`ls home\docs\customers\*.$1 2>/dev/null | wc -w`
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download