- Learn Shell - Free Interactive Shell Tutorial (2024)

Tutorial

Arguments can be passed to the script when it is executed, by writing them as a space-delimited list following the script file name.

Inside the script, the $1 variable references the first argument in the command line, $2 the second argument and so forth.The variable $0 references to the current script. In the following example, the script name is followed by 6 arguments.

Example

my_shopping.sh file contains below code.

#!/bin/bashecho "File name is "$0 # holds the current scriptecho $3 # $3 holds bananaData=$5echo "A $Data costs just $6."echo $#

Executing the script on terminal as,

bash my_shopping.sh apple 5 banana 8 "Fruit Basket" 15

output is

File name is my_shopping.sh

banana

A Fruit Basket costs just 15

6

The variable $# holds the number of arguments passed to the script

The variable $@ holds a space delimited string of all arguments passed to the script

Exercise

Pass "Shell is fun" (3 arguments) to the script(prog.sh) as an arguments and print the length of the arguments.

Tutorial Code

#!/bin/bashfunction File { # think you are inside the file # Change here echo "print the arguments"}# Do not change anythingif [ ! $# -lt 1 ]; then File $* exit 0fi# change here# here you can pass the argumentsbash test.sh arguments

Solution

#!/bin/bashfunction File { # think you are inside the file # Change Here echo $#}# Do not change anythingif [ ! $# -lt 1 ]; then File $* exit 0fi# change here# here you can pass the argumentsbash prog.sh Shell is fun

Expected Output

3
- Learn Shell - Free
    Interactive Shell Tutorial (2024)
Top Articles
Latest Posts
Article information

Author: Terence Hammes MD

Last Updated:

Views: 6089

Rating: 4.9 / 5 (49 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Terence Hammes MD

Birthday: 1992-04-11

Address: Suite 408 9446 Mercy Mews, West Roxie, CT 04904

Phone: +50312511349175

Job: Product Consulting Liaison

Hobby: Jogging, Motor sports, Nordic skating, Jigsaw puzzles, Bird watching, Nordic skating, Sculpting

Introduction: My name is Terence Hammes MD, I am a inexpensive, energetic, jolly, faithful, cheerful, proud, rich person who loves writing and wants to share my knowledge and understanding with you.