tags:

views:

284

answers:

5

How do I validate that the LOGNAME is present in a bash script

if [`logname`]; then
    echo -e \\t "-- Logname : `logname`" >> $normal_output_filename
fi

The above gives me an error line 76: [logname]: command not found

+1  A: 

When using backticks like this:

   `logname`

you execute the command logname. I guess it is not intended, is it?

Take a look at command substitution in Bash Beginners Guide.

Grzegorz Oledzki
if [logname]; thenDoes not evaluate true or false - I will try the other suggestions but thanks for the link, it was very useful.
Ian Warner
+3  A: 

Maybe try:

if [ -e /bin/logname ]; then
    LOGNAME=`logname`
    echo -e \\t "-- Logname : ${LOGNAME}" >> $normal_output_filename
fi

Actually, instead of using backtics it's better to use command substitution, namely:

LOGNAME=$(logname)

Using this syntax allows you to easily nest command substitutions without having to worry about layers of backslashes which is the case when using the older backtic syntax.

HTH

cheers,

Rob Wells
This works perfectly thank you.
Ian Warner
A: 

You could try using the "which" command to see if the specified command exists:

if which logname >/dev/null 2>&1; then
     #do something here
fi
Jason Musgrove
A: 

OK. Another answer. Not quite sure if fits you, but:

if test -n `logname`; then
    echo -e \\t "-- Logname : `logname`"
fi

I guess in the if you want to check if the logname command returns anything (when it's not?). If it is, then print it.

test -n checks if the next argument is an empty string.

Grzegorz Oledzki
it prints - logname: no login name
Ian Warner
+2  A: 
if [ `logname` ]; then
    echo -e \\t "-- Logname : `logname`" >> $normal_output_filename
fi

Mind the space between [ and `.

antreality