Bash 将位置参数传递给函数
我在尝试将参数传递给函数时遇到错误Bash 将位置参数传递给函数,bash,Bash,我在尝试将参数传递给函数时遇到错误 #! /usr/local/bin/bash program=$(basename $0) file_info () { # file_info: function to display file infomation. echo "this is $1" if [[ -e $1 ]]; then echo "Paramater 1 eq $1"
#! /usr/local/bin/bash
program=$(basename $0)
file_info () {
# file_info: function to display file infomation.
echo "this is $1"
if [[ -e $1 ]]; then
echo "Paramater 1 eq $1"
echo -e "\nFile Type:"
file "$1"
echo -e "\n File Status:"
stat "$1"
else
echo "$program: usage: $program file" >&2
return 1
fi
}
file_info
我测试它
$ bash file_info.sh answer.sh
this is .
file_info.sh: usage: file_info.sh file
尽管如此,该文件仍然存在
$ [[ -e answer.sh ]] && echo "answer.sh exists"
answer.sh exists
如何将位置参数传递给函数。要将脚本参数传递给函数,请将最后一行更改为:
file_info "$@"
必须引用$@吗?unquoted可以正常工作。@tool:这是必需的。Unquoted不能正确处理所有参数;只是碰巧你试过的那些。如果参数包含空格或全局字符(如
*
)等,则该选项无效。引号不需要额外收费。@Tool,我建议您查看错误或学习良好做法,请使用