Wolfy
Wolfy

Reputation: 4373

Print current command with echo?

I have a script that I copyed in /usr/bin/ups

In this script I print usage with this:

if [ ! $# == 1 ]; then
   echo "Usage: $0 {start|stop|restart|status}"
   exit
fi

when I run command "ups" I get this:

Usage: /usr/bin/ups {start|stop|restart|status}

How can I print usage like this:

Usage: ups {start|stop|restart|status}

The easyest way will be to do this:

if [ ! $# == 1 ]; then
   echo "Usage: ups {start|stop|restart|status}"
   exit
fi

but if some day I change the name of this file the usage text will be the same as before (ups).

Is there a nice way to do this?

Upvotes: 0

Views: 2355

Answers (5)

Paul
Paul

Reputation: 141829

Not sure if this is the best way, but you could do it like this:

COMMAND_NAME=${0##*/}
if [ "$(which $COMMAND_NAME 2> /dev/null)" != "$0" ]; then
    COMMAND_NAME=$0  
fi

if [ ! $# == 1 ]; then
   echo "Usage: $COMMAND_NAME {start|stop|restart|status}"
   exit
fi

Which will use the which command to determine if you're running the program from the PATH. Then display Usage: ups {start|stop|restart|status}, but if you use a relative path to it it will display that path instead: Usage: ../../usr/bin/ups {start|stop|restart|status}.

That is handy because if you ever take it out of the PATH it will still work correctly.

Upvotes: 0

Arnaud F.
Arnaud F.

Reputation: 8452

You can do:

echo "Usage: ${0##*/} {start|stop|restart|status}"

Upvotes: 1

abesto
abesto

Reputation: 2351

basename:

basename /usr/bin/ups  # outputs ups

Upvotes: 0

kev
kev

Reputation: 161614

You can change the

$0

to

${0##*/}

Upvotes: 2

unwind
unwind

Reputation: 399753

Use basename:

echo "Usage: $(basename $0) {start|stop|restart|status}"

Upvotes: 4

Related Questions