BLOG
ARTICLE

Flag Arguments in Shell Script

2 min read

Greetings! For the first post of 2022 I'd like to do something short but useful.

Most of us developers have used CLI commands before. Ever wonder how to get arguments from flags like this in shell script?

1
command -flag1 ARG -flag2 ARG

Turns out we can easily create our own flags definition with getopts. Take a look at the following script.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/usr/bin/env bash

FLAG_1=''
FLAG_2=''
FLAG_3=''
FLAG_4=''

while getopts 'a:b:c:d:' flag; do
  case "${flag}" in
  a) FLAG_1="${OPTARG}" ;;
  b) FLAG_2="${OPTARG}" ;;
  c) FLAG_3="${OPTARG}" ;;
  d) FLAG_4="${OPTARG}" ;;
  esac
done

echo "FLAG_1=$FLAG_1"
echo "FLAG_2=$FLAG_2"
echo "FLAG_3=$FLAG_3"
echo "FLAG_4=$FLAG_4"

Copy the above script to a file, give it any name like test.sh and run it on terminal with flags + arguments. You will get the results.

1
2
3
4
5
root@JerfarezaPC:/home/ubuntu# sh test.sh -a this -b are -c flag -d arguments 
FLAG_1=these
FLAG_2=are
FLAG_3=flag
FLAG_4=arguments

There you're done! ❤️

Notice the script doesn't throw error even when you're missing the flags? I wrote about more about shell scripts in my previous post 'Best Practices with Shell Script'. Consider this post as an extension to that.

Jerfareza Daviano

Hi, I'm Jerfareza
Daviano 👋🏼

Hi, I'm Jerfareza Daviano 👋🏼

I'm a Full Stack Developer from Indonesia currently based in Japan.

Passionate in software development, I write my thoughts and experiments into this personal blog.