V
V
Victor2014-09-01 19:25:23
linux
Victor, 2014-09-01 19:25:23

Why is the "$#" variable not visible in the bash function?

Hello. In general, the problem is this. There is a bash script, there is a function that checks the number of parameters passed to the script, and depending on whether the parameter is passed or not, the function performs certain actions. For example:
#!/bin/bash
function my_func() {
if [ $# -eq 0 ]; then
echo "0 parameters passed"
else
echo "$# parameters passed"
fi
}
my_func
but when calling the script and passing parameters to it, this variable "$#" is always equal to zero, although if you just write not in the body of the function echo "$#" , it will show the number of parameters passed to the script. The question is, why is it so, I can’t get it?
bash version 4.2.25(1)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
akarin, 2014-09-01
@estoy

The function has a local scope.

#!/bin/bash
if [ $# -eq 0 ]; then 
echo "Передано 0 параметров"
else
echo \"Передано $# параметров\"
fi

echo $1

S
safinaskar, 2014-09-25
@safinaskar

To pass exactly all the original arguments to the function, you can write this: my_func "[email protected]"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question