summaryrefslogtreecommitdiff
path: root/How to properly do options in a bash script with getopt!.md
blob: 5efe6d23db326d724103257be5fca45cd7d3b8eb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
---
tags:
  - bash
---
```
#!/bin/bash

while getopts "ab:c" opt; do
  case "$opt" in
    a)
      echo "Option -a was specified."
      ;;
    b)
      echo "Option -b was specified with argument: $OPTARG"
      ;;
    c)
      echo "Option -c was specified."
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
  esac
done

shift $((OPTIND - 1))

echo "Remaining arguments: $@"
```

man bash // getopt

The **colon** after b in getopts indicates that it has an argument.