Accepting logfile as parameter and calling a function if filename is passed but file doesn’t exist

I’m currently a bit confused regarding arguments and parameters for a question.

I currently have to accept the log filename as a parameter (For example, /var/log/secure-<yyyymmdd>) but default to /var/log/secure if no arguments are given.

How do I accept the log filename as a parameter? I think it might be the phrasing of the question, but I don’t quite get what it means.

This is a snippet of the current code I have done so far before this question:

#!/bin/bash
grep " su: " /var/log/secure | while read -r abc; do   
echo "$abc"
done

For the 2nd part, I have to create a function that exits with code 2 (I’m working on that currently) and afterwards, call that function if a filename is passed but the file doesn’t exist. Would I do something like this? It feels wrong but not sure where.

IF [ -d /var/log/secure ]
then

else
runfunction

Answer

To set a variable to the first command line argument, you would do

pathname=$1

To set it to a default value in case the argument is not available or if it’s empty, use

pathname=${1:-/var/log/secure}

The general form is ${parameter:-word}. This is a standard POSIX parameter expansion, and it’s also documented in the manual of your shell.

The -d test tests whether the given string corresponds to an existing directory path (or is a symbolic link to one that exists). The -f test is for regular files in the same way, and -e covers anything (will be true if the name exists, regardless of what it is a name of).

To negate the sense of a test, you would use !, so you get

if [ ! -f "$pathname" ]; then
    myfunction
fi

or, using short-circuit syntax,

[ ! -f "$pathname" ] && myfunction

This would call myfunction if the string in the pathname variable did not designate an existing regular file (or a link to one).


A complete script that takes a command line argument (a path) with a default value and exits with exit status 2 if the given path does not correspond to an existing regular file.

#!/bin/bash

pathname=${1:-/var/log/secure}

if [ ! -f "$pathname" ]; then
    printf 'There is no file called "%s"n' "$pathname"
    exit 2
fi

printf 'The file "%s" existsn' "$pathname"

Leave a Reply

Your email address will not be published. Required fields are marked *