Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count and check passed arguments?

How can I translate the following Ruby code to Bash?

if ARGV.length == 0
    abort "\nError: The project name is required. Aborting...\n\n"
elsif ARGV.length > 2
    abort "\nError: The program takes two arguments maximum. Aborting...\n\n"
end
like image 388
emurad Avatar asked Jun 04 '11 19:06

emurad


2 Answers

#!/bin/bash
USAGE="$0: <project name> [subproject attribute]"
if [ $# -lt 1 ]; then echo -e "Error: The project name is required.\n$USAGE" >&2; exit 1; fi
if [ $# -gt 2 ]; then echo -e "Error: Two arguments maximum.\n$USAGE" >&2; exit 1; fi
like image 168
Seth Robertson Avatar answered Nov 12 '22 16:11

Seth Robertson


The following should be what you need:

#!/bin/bash
if [ $# -eq 0 ]; then
  echo -e "\nError: The project name is required. Aborting...\n\n"
  exit 1
elif [ $# -gt 2 ]; then
  echo -e "\nError: The program takes two arguments maximum. Aborting...\n\n"
  exit 1
fi

The TLDP bash guide is very good if you are looking to learn bash, see TDLP Bash guide.

like image 4
MGwynne Avatar answered Nov 12 '22 16:11

MGwynne