Reputation: 4373
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
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