Bash test if an argument exists
11,004
Solution 1
The simplest solution would be:
if [[ " $@ " =~ " -h " ]]; then
echo "Has -h"
fi
Solution 2
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.
Solution 3
#!/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.
Author by
Aleksandr Levchuk
Updated on October 16, 2022Comments
-
Aleksandr Levchuk over 1 year
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?
-
Jonathan Leffler almost 13 yearsThe option is not removed. The trick to reparsing the argument list is to reset
OPTIND=0
between thegetopts
loops. -
Aleksandr Levchuk almost 13 yearsUnderstood. Verified. Answer corrected. Thanks to Jonathan Leffler for all the tips that lead to this answer.
-
logidelic almost 5 yearsNote that for me this outputs "has -h" multiple times, even though
-h
was only specified once as an argument... -
Cecil Curry about 3 yearsWhile clever, this reports false positives for arguments that are strings embedding the substring ` -h ` (e.g.,
my_command "oh gods -h game over"
). The only general-purpose solution is to iterategetopts
results as detailed below.</shrug>
-
kitingChris about 3 yearstrue! Today I also would endorse getopts. The simple solution is more a wonky hack...