@@ -5,41 +5,78 @@ Arguments can be passed to the script when it is executed, by writing them as a
5
5
Inside the script, the $1 variable references the first argument in the command line, $2 the second argument and so forth.
6
6
The variable $0 references to the current script. In the following example, the script name is followed by 6 arguments.
7
7
8
- ** ./bin/my_shopping.sh apple 5 banana 8 "Fruit Basket" 15**
8
+ Example
9
+ -------------
10
+ my_shopping.sh file contains below code.
11
+
12
+ #!/bin/bash
13
+ echo "File name is "$0 # holds the current script
14
+ echo $3 # $3 holds banana
15
+ Data=$5
16
+ echo "A $Data costs just $6."
17
+ echo $#
9
18
10
- ** echo $3 --> results with: banana **
19
+ Executing the script on terminal as,
11
20
12
- ** BIG=$5 **
21
+ ** bash my_shopping.sh apple 5 banana 8 "Fruit Basket" 15 **
13
22
14
- ** echo "A $BIG costs just $6" --> results with: A Fruit Basket costs just 15 **
23
+ output is
15
24
16
- The variable $# holds the number of arguments passed to the script
25
+ ** File name is my_shopping.sh **
17
26
18
- ** echo $# --> results with: 6**
27
+ ** banana**
28
+
29
+ ** A Fruit Basket costs just 15**
30
+
31
+ ** 6**
32
+
33
+ The variable $# holds the number of arguments passed to the script
19
34
20
35
The variable $@ holds a space delimited string of all arguments passed to the script
21
36
22
37
Exercise
23
38
-------------
24
- Pass "Shell is fun" (3 arguments) to the script as an array and print the length of the array .
39
+ Pass "Shell is fun" (3 arguments) to the script(prog.sh) as an arguments and print the length of the arguments .
25
40
26
41
Tutorial Code
27
42
-------------
28
43
#!/bin/bash
29
- #To pass three arguments
30
- args=("$@")
31
- echo ${args[0]} ${args[1]} ${args[2]}
32
- echo $# #prints the length f the array
44
+ function File {
45
+ # think you are inside the file
46
+ # Change here
47
+ echo "print the arguments"
48
+ }
49
+
50
+ # Do not change anything
51
+ if [ ! $# -lt 1 ]; then
52
+ File $*
53
+ exit 0
54
+ fi
55
+
56
+ # change here
57
+ # here you can pass the arguments
58
+ bash test.sh arguments
33
59
34
60
Solution
35
- --------
36
- #!/bin/bash
37
- args=("Shell" "is" "fun")
38
- echo ${args[ 0] } ${args[ 1] } ${args[ 2] }
39
- echo ${#args[ @] }
61
+ -------------
62
+ #!/bin/bash
63
+ function File {
64
+ # think you are inside the file
65
+ # Change Here
66
+ echo $#
67
+ }
68
+
69
+ # Do not change anything
70
+ if [ ! $# -lt 1 ]; then
71
+ File $*
72
+ exit 0
73
+ fi
74
+
75
+ # change here
76
+ # here you can pass the arguments
77
+ bash prog.sh Shell is fun
78
+
40
79
41
80
Expected Output
42
81
---------------
43
- Shell is fun
44
82
3
45
-
0 commit comments