Bash, Shell Script: How To Use Positional Parameters, Invoking A Function Part 1

bash_eyecatch 冒険

Added——
Link to Part2 “how to prompt and read user input after starting executing the script and how to pass it to the function as the argument”
——deddA

Firstly, positional parameters points to the name of any executed command or script and things following them, like arguments or options, on a command line, look at the next sample command line;

$ script_echos “Hello” “World!”

In this case, the first positional parameter is script_echos, which is the name of executed script here written by me, it is represented by $0.

Then $1 is “Hello” and $2 is “World!”.

Then, if you want to pass values of positional parameters to any function invoked in script’s main part , how it can be done?

Look the next sample code and its output below;

#!/bin/bash

### Function

echos() {
echo $1
echo $2
echo “Can you see?”
}

### Main

echos
return 0

$ script_echos “Hello” “World!”

 
Can you see?

As you see, $1 “Hello” and $2 “World!” are not display as the output, so I have confused as to why this script does not work as I expect, at function defining section, I set $0 to $2 as argument to echo command though.

But it was found that the solution is very easy, but up to now I have not gotten it.
Look the modified code and its output below;

#!/bin/bash

### Function

echos() {
echo $1
echo $2
echo “Can you see?”
}

### Main
echos $1 $2
return 0

$ script_echos “Hello” “World!”
Hello
World!
Can you see?

As you see, the problem is using positional parameters is not specified as arguments at invoking the function “echos” in the main part. This shows the specification has to be done, even if it is written on the function defining section.

Link to Part2 “how to prompt and read user input after starting exectuting the script and how to pass it to the function as the argument”

タイトルとURLをコピーしました