4

There is program I use, say xyz, that has undesirable effects if I run the command bare with no arguments. So I'd like to prevent myself from accidentally running the xyz command with no arguments but allow it to run with arguments.

How can I write a shell script so that when calling xyz with no arguments it will print an error message and otherwise pass any and all arguments to the xyz program?

2 Answers 2

11

You can check special variable $#:

if [ $# -eq 0 ]; then
  echo "No arguments provided!"
  exit 1
fi
/usr/bin/xyz "$@"

Then, add an alias to your ~/.bashrc;

alias xyz="/path/to/script.sh"

Now, each time you run xyz, the alias will be launched instead. This will call the script which checks whether you have any arguments and only launches the real xyz command if you do. Obviously, change /usr/bin/xyz to whatever the full path of the command is.

0
0

In most cases the frame can be

if [ "$1" ]
then
  /usr/bin/xyz "$@"
else
  echo "Errormessage"
fi 
7
  • 2
    This will fail if $1 is empty. See my comment in @chaos's answer.
    – cuonglm
    Nov 12, 2014 at 14:06
  • @cuonglm In my bash version it is not. Checked set -- ; [ "$1" ] ; echo $? produce 1 without any error.
    – Costas
    Nov 12, 2014 at 14:25
  • In order for this to be useful, the script must be named xyz so this will cause an endless loop since you're not using the full path to xyz.
    – terdon
    Nov 12, 2014 at 14:26
  • @terdon Or even to be a such bash function xyz() {...}
    – Costas
    Nov 12, 2014 at 14:28
  • Well, in a function, the exit causes the terminal to exit but you can just remove it, it's not really needed. The main issue is that unless you use the full path, the function/script/whatever will keep calling itself and enter an infinite loop.
    – terdon
    Nov 12, 2014 at 14:36

You must log in to answer this question.

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