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?
You can use either "=" or "==" operators for string comparison in bash. The important factor is the spacing within the brackets.
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"
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.
The simplest solution would be:
if [[ " $@ " =~ " -h " ]]; then
echo "Has -h"
fi
#!/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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With