bash - 从函数内部检查脚本命令行参数

标签 bash

我有以下非常简单的脚本:

#!/bin/bash

checkCmdLineArgs() {
    echo -e "num input args $#"
    if (( $# == 0 )); then
        echo "$0 usage: install_dir home_dir"
        exit 255
    fi
}

checkCmdLineArgs

它不起作用。如果我像这样运行它:

./test.sh foo bar

它输出:

num input args 0
./test.sh usage: install_dir home_dir

知道为什么失败吗?

最佳答案

在函数内部,$#$@$1 及以后引用函数的参数列表,而不是脚本的参数列表。 ($0 是一个异常(exception),仍然会引用在脚本本身的第一个 argv 位置传递的名称;请注意,虽然这通常是脚本的名称,但它不是不能保证是真的)。​​

将脚本的参数传递给函数:

checkCmdLineArgs "$@"

关于bash - 从函数内部检查脚本命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46004301/

相关文章:

bash 突破读取内部陷阱

bash - 使用 While 和 grep 组合 - "syntax error near unexpected token ` <' "

windows - 将 %ComSpec% 从 cmd.exe 更改为 bash.exe

linux - awk inside shell脚本显示/etc/passwd信息

python - 从 python 脚本导入 shell 变量

javascript - 尝试将 BASH 安装到 VSCode 时无法编辑用户设置。 "terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe",

android - ADB shell sendevents 不工作

Linux sftp 服务器上的权限问题

linux - 仅在 alpine linux 上出现算术语法错误

ruby - 为什么我不能运行 postgresql 服务器?