【问题标题】:Pass arguments from command Line and from function inside shell script从命令行和 shell 脚本中的函数传递参数
【发布时间】:2016-12-17 09:23:06
【问题描述】:

我想知道天气可以从命令行和shell脚本中的函数传递参数

我知道可以使用

将参数从命令行传递到 shell 脚本
$1 $2 ..

但我的问题是我的 shell 脚本需要接受来自命令行的参数以及 shell 脚本中的函数。

在下面找到我的 shell 脚本

#!/bin/bash

extractZipFiles(){
  sudo unzip  "$4" -d "$5"
  if [ "$?" -eq 0 ]
  then
    echo "==>> Files extracted"
    return 0
  else
    echo "==>> Files extraction failed"
    echo "$?"
  fi
}

coreExtraction(){
extractZipFiles some/location some/other/location
}

coreExtraction

echo "====> $1"
echo "====> $2"
echo "====> $3"
echo "====> $4"
echo "====> $5"

我通过传递来执行我的 shell 脚本

sudo sh test.sh firstargument secondargument thirdargument 

【问题讨论】:

    标签: linux bash shell ubuntu sh


    【解决方案1】:

    您可以通过以下方式转发原始参数:

    ...
    coreExtraction () {
        extractZipFiles "$@" some/location some/other/location
    }
    coreExtraction "$@"
    ...
    

    要从函数内部访问原始脚本参数,您必须在调用函数之前将它们保存在例如数组中:

    args=("$@")
    some_function some_other_args
    

    some_function 中,脚本参数将在${args[0]}${args[1]} 等中。他们的电话号码是${#a[@]}

    【讨论】:

      【解决方案2】:

      只需将命令行调用中的参数传递给函数

      coreExtraction "$1" "$2" "$3"
      # or
      coreExtraction "$@"
      

      并向它们添加其他参数

      extractZipFiles "$@" some/location some/other/location
      

      【讨论】:

      • 谢谢@choroba ..我不想将相同的参数从命令行传递给shell脚本中的函数,我需要将不同的参数传递给shell脚本中的函数..有没有办法做到这一点。
      • 在我的回答中解决了这个问题。
      • @SpencerBharath:传递你需要的任何参数。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 2013-03-03
      相关资源
      最近更新 更多