About Parameters in bash
- A parameter is an entity that stores values.
- There are three types of parameters:
- positional parameters
- special parameters
- variables
- We'll discuss here only positional parameters.
(the other types will be discussed in other posts)
Positional Parameters
- These are arguments present you give a script you are running.
You reference them by using $ and the position.
- Here's an example:
1$
2$ ls -l
3total 4
4-rwxrw-r-- 1 osboxes osboxes 89 Jan 17 09:29 three
5$
6$ cat three
7#!/bin/bash
8#
9echo "positional 1 " $1
10echo "positional 2 " $2
11echo "positional 3 " $3
12$
13$ ./three
14positional 1
15positional 2
16positional 3
17$
Using parameters with curly braces
- Let's say you have 10 parameters.
Here's what I got:
1$ cat ten
2#!/bin/bash
3#
4echo "positional 1 " $1
5echo "positional 2 " $2
6echo "positional 3 " $3
7echo "positional 4 " $4
8echo "positional 5 " $5
9echo "positional 6 " $6
10echo "positional 7 " $7
11echo "positional 8 " $8
12echo "positional 9 " $9
13echo "positional 10 " $10
14$
15$ ./ten one two three four five six seven eight nine ten
16positional 1 one
17positional 2 two
18positional 3 three
19positional 4 four
20positional 5 five
21positional 6 six
22positional 7 seven
23positional 8 eight
24positional 9 nine
25positional 10 one0
26$
- Note what happened in the 10th parameter. It was used as $1 with '0' attached to it.
To change that use braces:
1$ cat ten
2#!/bin/bash
3#
4echo "positional 1 " $1
5echo "positional 2 " $2
6echo "positional 3 " $3
7echo "positional 4 " $4
8echo "positional 5 " $5
9echo "positional 6 " $6
10echo "positional 7 " $7
11echo "positional 8 " $8
12echo "positional 9 " $9
13echo "positional 10 " ${10}
14$
15$ ./ten one two three four five six seven eight nine ten
16positional 1 one
17positional 2 two
18positional 3 three
19positional 4 four
20positional 5 five
21positional 6 six
22positional 7 seven
23positional 8 eight
24positional 9 nine
25positional 10 ten
26$