Bash – Shell script wrapper to prevent running command with no arguments

bashshell-script

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?

Best Answer

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.

Related Question