[英]Command line argument not working when passing to a function while using getopts
I've been trying to get some practice in with bash shell scripting but I've been having trouble using the $1 variable to reference the first argument for my script. 我一直在尝试使用bash shell脚本进行练习,但是在使用$ 1变量引用脚本的第一个参数时遇到了麻烦。 It's a simple script that takes a file as an argument and prints the name of the file.
这是一个简单的脚本,将文件作为参数并显示文件名。 Here's my script:
这是我的脚本:
#!/bin/bash
function practice() {
echo "${1}"
}
while getopts "h:" opt; do
case "$opt" in
h) practice
;;
esac
done
exit 0
I tried the following command: 我尝试了以下命令:
./practice.sh -h somefile.txt
For some reason it returns an empty line. 由于某种原因,它返回一个空行。 Any thoughts?
有什么想法吗?
$1
in functions refers to first positional parameter passed to that function, not passed to your script. 函数中的
$1
传递给该函数而不是传递给脚本的第一个位置参数。
Therefore, you have to pass the arguments you want to the function again. 因此,您必须再次将所需的参数传递给函数。 You also tell
getopts
you want to process -h
but then you are checking for -a
in your case
instead: 你也告诉
getopts
要处理-h
但随后你检查-a
在你的case
,而不是:
#!/bin/bash
practice() {
echo "${1}"
}
while getopts "h:" opt; do
case "$opt" in
h) practice "${OPTARG}"
;;
esac
done
#!/bin/bash
function practice() {
echo "${1}"
}
while getopts "h:" opt; do
case "$opt" in
a) practice $*
;;
esac
done
exit 0
pass the command line arguments to the function as above. 将命令行参数传递给上述函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.