user6348718
user6348718

Reputation: 1395

how to pass parameter to a function when it's called inside another function in shell

I have shell script with 2 functions like below:

lines(){
    while IFS="" read -l
    do
        line=$(wc -l < "something.txt")
        if [ "$line" = "$1" ] ; then
           do something...
           echo "lines are: "$l""       
        else

         #calling files function here
         files
         do something...
         fi
    done<something.txt
}
files(){
    do something....
    echo "something...\n""$(lines "$1")"
}
####Main
case "$1" in
   lines)
        shift
        lines "$1"
        ;;
   *)
esac

I am trying to run the script like this on an ubuntu machine:

 sh files.sh line 3

I have some if operations where In files I am trying to call lines function. When it's called and goes back to perform the actions in lines(), the argument I am trying to pass from the command line 3 i.e., "$1" is being passed as null (empty) Can someone help me how I can have lines function read the parameter I am passing from the command line Thanks

Upvotes: 1

Views: 4116

Answers (2)

Barmar
Barmar

Reputation: 780673

Positional parameters are local to each function. So files can't access the $1 variable of lines by itself, you need to pass it explicitly:

files "$1"

Upvotes: 1

Charles Duffy
Charles Duffy

Reputation: 295281

The easy thing to do is to just create a global array variable that preserves your original command-line arguments:

#!/usr/bin/env bash
[ "$BASH_VERSION" ] || { echo "ERROR: This script requires bash" >&2; exit 1; }

args=( "$0" "$@" )

func1() { func2 "local-arg1" "local-arg2"; }
func2() { echo "Function argument 1 is $1; original argument 2 is ${args[2]}"; }
func1

...will, if called as ./scriptname global-arg1 global-arg2, emit as output:

Function argument 1 is local-arg1; original argument 2 is global-arg2

Upvotes: 2

Related Questions