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:

grep " su: " /var/log/secure | while read -r abc; do   
echo "$abc"

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 ]


1 Answer 1


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


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


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

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.



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

printf 'The file "%s" exists\n' "$pathname"
  • Thanks, so following the if statement, would this work pathname=${1:-/var/log/secure} exitcode() { exit 2 } if [ ! -f "$pathname" ]; then exitcode fi (Sorry, not sure how to format a comment but this is how it looks i.imgur.com/5cHQpJD.png ) Sep 13, 2018 at 20:17
  • @Zanders2001 Yes, but I so real point in using the function when you can just conditionally call exit 2 directly.
    – Kusalananda
    Sep 13, 2018 at 20:19
  • I think its just to get a general idea of it, this is our first script that we've worked on in class (And my first bash script). Also regarding the first question, I'm still a bit confused about accepting log filename as a parameter. This is what I have so far i.imgur.com/WTx6nPR.png Sep 13, 2018 at 20:32
  • @Zanders2001 See updated answer.
    – Kusalananda
    Sep 13, 2018 at 21:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .