Bash 函数 - 函数中的第二个参数未被采用

Bash function - second parameter in a function not taken

出于某种原因,我无法将第二个参数传递给另一个文件上的函数,就在这里:

$lsValidLocal | xargs -n 1 -I {} bash -c 'Push "{}" "**$inFolder**"

functions.sh 上的 Push 函数不读取第二个参数 $inFolder.

我尝试了几种不同的方法,到目前为止唯一可行的方法是导出变量以使其全局可访问(虽然不是一个好的解决方案)

script.sh

#!/bin/bash
#other machine
export otherachine="IP_address_otherachine"

#folders
inFolder="$HOME/folderIn"

outFolder="$HOME/folderOut"

#loading functions.sh
. /home/ec2-user/functions.sh

export lsValidLocal="lsValid $inFolder"

echo $inFolder

#execution
$lsValidLocal  | xargs -n 1 -I {} bash -c 'Push "{}" "$inFolder"'

functions.sh

function Push() { 
        local FILE=
        local DEST=

        scp $FILE $otherachine:$DEST &&
        rm $FILE ${FILE}_0 &&
        ssh $otherachine "touch ${FILE}_0"
}

function lsValid() { #from directory
        local DIR=

        ls $DIR/*_0  | sed 's/.\{2\}$//'
}


export -f Push
export -f Pull
export -f lsValid

您编写的代码的问题在于 $inFolder 位于单引号 (') 内,这将阻止它展开。

$lsValidLocal  | xargs -n 1 -I {} bash -c 'Push "{}" "**$inFolder**"'

这将作为三个独立的进程层执行

bash <your scrpit>
|
\xargs ...
  |
  \bash -c Push ...

您的代码没有将值从外部 shell 转移到内部 shell...但是您正在使用内部 shell 扩展变量 inFolder .正如您正确指出的那样,可以使用导出的环境变量来完成。

另一种方法是让外部 shell 在传递给 xargs 之前展开它。

$lsValidLocal  | xargs -n 1 -I {} bash -c "Push '{}' '**$inFolder**'"

请注意,我已反转 '" 以允许在调用 xargs 之前扩展 $inFolder