I am writing a bash script and I want send a parameter to my script from outside which starts with a hyphen (-) like this '-d'.
However, I am getting following warnings when I execute my script
dirname: invalid option -- 'd'
I am saying warnings as I can see my script is working despite of this. But I want to get rid of these warnings too. Can anybody help?
For more clarification, I am executing the script like this-
sh script.sh <param1> -d <param2>
Attaching a code snippet from the script where this argument is being used
case ${2} in
-d|--days) timeUnit="d";;
-h|--hours) timeUnit="h";;
That is not a warning, it is an error.
If you want to pass a file name that begins with a dash to dirname then you have two options:
dirname -- -d
or
dirname ./-d
Based on your invocation line, we can infer that you must be incorrectly relaying the -d argument from your script's argument list to the argument list that is given to the dirname call that is being invoked from inside your script.
You're probably doing something like this inside your script:
dirname "$@"
or maybe
dirname "$2"
either of which will pass the -d argument to dirname.
You need to properly parse your script's arguments and only pass the option value of your script's -d option to the dirname call. This process is often referred to as options processing.
Here's an example of how you can do options processing:
dir='';
nonOpt=();
for ((i = 1; i <= $#; ++i)); do
arg="${@:$i:1}";
if [[ "$arg" == '--' ]]; then
nonOpt+=("${@:$i+1}");
break;
elif [[ "$arg" == -?* ]]; then
case "${arg:1}" in
(d|dir)
if [[ $i -eq $# ]]; then printf 'error: trailing -d option.\n' >&2; exit 1; fi;
let ++i;
dir="${@:$i:1}";
;;
(h|help)
printf 'script.sh [-h|--help] {param1} -d|--dir {dir}\n' >&2;
exit 1;
;;
(*)
printf "error: invalid option: $arg.\\n" >&2;
exit 1;
;;
esac;
else
nonOpt+=("$arg");
fi;
done;
if [[ ${#nonOpt[@]} -ne 1 ]]; then printf 'error: require 1 non-option argument.\n' >&2; exit 1; fi;
param1="${nonOpt[0]}";
if [[ "$dir" == '' ]]; then printf 'error: missing {dir}.\n' >&2; exit 1; fi;
dirname -- "$dir";
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