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?
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?
It is modestly complex. The quickest way is also unreliable:
case "$*" in
(*-h*) echo "Has -h";;
esac
Unfortunately that will also spot "command this-here
" as having "-h
".
Normally you'd use getopts
to parse for arguments that you expect:
while getopts habcf: opt
do
case "$opt" in
(h) echo "Has -h";;
([abc])
echo "Got -$opt";;
(f) echo "File: $OPTARG";;
esac
done
shift (($OPTIND - 1))
# General (non-option) arguments are now in "$@"
Etc.
#!/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.
I found the answer in a dupe question here: https://serverfault.com/questions/7503/how-to-determine-if-a-bash-variable-is-empty
See my function mt() below for an example usage:
# mkdir -p path to touch file
mt() {
if [[ -z $1 ]]; then
echo "usage: mt filepath"
else
mkdir -p `dirname $1`
touch $1
fi
}
The simplest solution would be:
if [[ " $@ " =~ " -h " ]]; then
echo "Has -h"
fi