【问题标题】:Bash script not recognizing command-line arguments? [duplicate]Bash 脚本无法识别命令行参数? [复制]
【发布时间】:2021-11-25 04:16:18
【问题描述】:

我正在使用命令 ./mkproj.sh 调用 bash 脚本 mkproj.sh。我也尝试使用参数调用它: ./mkproj.sh hello 但是当我在脚本中放置 echo "$1" 时,我的脚本返回一个空值 $1。我不确定为什么它不能识别命令行参数。

check_for_file()
{
if [ $# -eq 0 ]; then
        local testing_file=myproject
else
        local testing_file=$1
fi

if [ -d $testing_file ]; then
        echo "Directory name already exists"
        exit
else
        mkdir -p "$testing_file"/{archive,backups,docs/{html,txt},assets,database,src/{sh,c}}
fi

}
check_for_file


谢谢!

【问题讨论】:

  • 请添加合适的 shebang (#!/bin/bash),然后将您的脚本粘贴到 shellcheck.net 并尝试实施那里提出的建议。
  • $1 是函数的第一个参数。你调用了没有参数的函数,所以 $1 没有定义。

标签: bash unix positional-parameter


【解决方案1】:

函数中的位置参数阴影全局位置 脚本接收到的参数。你需要调用你的函数 那:

check_for_file "$1"

【讨论】:

  • How to Answer 中,请注意回答正确提出的问题 部分,以及其中关于“之前已被多次询问和回答”的问题的要点。跨度>
猜你喜欢
  • 2017-11-19
  • 2015-09-10
  • 2022-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多