【问题标题】:Bash - Calling Function of Master script with passing argument from child scriptBash - 通过子脚本传递参数调用主脚本的函数
【发布时间】:2019-09-20 07:34:47
【问题描述】:

我有一个很少有函数定义的主脚本。使用子脚本即时尝试调用主脚本并将参数传递给函数。这里的问题是我的主脚本被执行了两次。 1.每次我调用我的子脚本时,首先主脚本中的所有函数都在没有任何参数的情况下执行(即空参数) 2. 然后第二次参数值被传递并按预期成功执行函数。

请告诉我如何避免执行上面指定的步骤 1。

我尝试过使用 source (or) 。然后在子脚本中指定主脚本,然后指定函数名称和参数。但它不起作用。

子脚本:


source <directory_path>/master.sh 
add '123' 'get' 'R'

主脚本:


#! /bin/bash

add()
{
exec &> $1_$(date "+%Y%m%d%H%M").log
Change=$1
Command=$2
if [[ $Command == "get" ]];
then Command_1="getfacl"
elif [[ $Command == "set" ]];
then Command_1="setfacl"
elif [[ $Command == "ch" ]];
then Command_1="chown"
else Command_1="ls"
fi
Tag=$3
if [[ -z "$Tag" ]];
then Tag=""
else Tag="-$Tag"
fi
}
add;

子脚本:


source <directory_path>/master.sh 
add '123' 'get' 'R'

根据脚本只能生成一个文件。但实际结果会生成2个文件。

预期结果


123_201909201012.log 

实际结果


_201909201012.log 
123_201909201012.log

【问题讨论】:

    标签: bash function shell


    【解决方案1】:

    在你的函数声明之后,你立即执行它:

    add()
    {
    ...
    }
    add; # you execute it here... remove this line
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-08
      • 2011-10-10
      • 1970-01-01
      • 2023-03-05
      • 2014-03-01
      • 2015-05-13
      • 2019-10-16
      • 2014-10-04
      相关资源
      最近更新 更多