将命令传递给函数

Passing commands to a function

我在尝试将一些复杂的命令作为参数传递给函数时遇到了问题。

    function executeCmd(){
    
    returnVal=$?
    if [[ $returnVal -eq 0 ]]; then
        echo "Success"
    else
        echo "Failed"
    fi
}

executeCmd "ssh $USER@$IP "date && (ls | grep "something")""

我尝试了不同的引号、转义字符,但我遗漏了一些东西。 提前致谢!

不要尝试在状态函数中执行命令;只需在 调用命令后 调用以下函数:

status () {
  if [[ $? == 0 ]]; then
    echo "Success"
  else
    echo "Failure"
  fi
}

例如:

ssh $USER@$IP "date && (ls | grep \"something\")"; status

有关详细信息,请参阅 I'm trying to put a command in a variable, but the complex cases always fail!。 (本质上,您试图将命令放在函数的第一个位置参数 中。)