Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash test if an argument exists

I want to test if an augment (e.g. -h) was passed into my bash script or not.

In a Ruby script that would be:

#!/usr/bin/env ruby
puts "Has -h" if ARGV.include? "-h"

How to best do that in Bash?

like image 387
Aleksandr Levchuk Avatar asked Jun 02 '11 22:06

Aleksandr Levchuk


People also ask

How do you check if an argument is a string bash?

You can use either "=" or "==" operators for string comparison in bash. The important factor is the spacing within the brackets.

How do I check if an argument is empty in bash?

To find out if a bash variable is empty: Return true if a bash variable is unset or set to the empty string: if [ -z "$var" ]; Another option: [ -z "$var" ] && echo "Empty" Determine if a bash variable is empty: [[ ! -z "$var" ]] && echo "Not empty" || echo "Empty"

How do you check if the second argument is passed in shell script?

The if [ $# -eq 0 ] part you can add to the script, and change the 0 to some other numbers to see what happens. Also, an internet search for "bash if" will reveal the meaning of the -eq part, and show that you could also use -lt or -gt , for instance, testing whether a number is less than or greater than another.


2 Answers

The simplest solution would be:

if [[ " $@ " =~ " -h " ]]; then
   echo "Has -h"
fi
like image 160
kitingChris Avatar answered Oct 04 '22 08:10

kitingChris


#!/bin/bash
while getopts h x; do
  echo "has -h";
done; OPTIND=0

As Jonathan Leffler pointed out OPTIND=0 will reset the getopts list. That's in case the test needs to be done more than once.

like image 34
Aleksandr Levchuk Avatar answered Oct 04 '22 08:10

Aleksandr Levchuk