我可以将任意命令块传递给bash函数吗?

时间:2020-03-06 14:28:01  来源:igfitidea点击:

我正在使用bash脚本,如果存在特定文件,则需要有条件地执行一些操作。这是多次发生,所以我抽象了以下函数:

function conditional-do {
    if [ -f  ]
    then
        echo "Doing stuff"
        
    else
        echo "File doesn't exist!"
    end
}

现在,当我要执行此操作时,我将执行以下操作:

function exec-stuff {
    echo "do some command"
    echo "do another command"
}
conditional-do /path/to/file exec-stuff

问题是,我烦恼的是我要定义两件事:一组要执行的命令的功能,然后调用我的第一个功能。

我想以一种干净的方式直接将此命令块(通常是2个或者更多)传递给"条件执行",但是我不知道这是如何实现的(或者甚至是可能的)...有人吗?有任何想法吗?

请注意,我需要它是一个可读的解决方案...否则,我宁愿坚持使用我拥有的东西。

解决方案

一种(可能是黑客)解决方案是将单独的功能存储为单独的脚本。

对于大多数C程序员来说,这应该是可读的:

function file_exists {
  if ( [ -e  ] ) then 
    echo "Doing stuff"
  else
    echo "File  doesn't exist" 
    false
  fi
}

file_exists filename && (
  echo "Do your stuff..."
)

或者单线

file_exists filename && echo "Do your stuff..."

现在,如果我们确实希望从该函数运行代码,则可以这样做:

function file_exists {
  if ( [ -e  ] ) then 
    echo "Doing stuff"
    shift
    $*
  else
    echo "File  doesn't exist" 
    false
  fi
}

file_exists filename echo "Do your stuff..."

不过,我不喜欢这种解决方案,因为我们最终将不得不转义命令字符串。

编辑:将"评估$ *"更改为$ *。实际上,不需要评估。与bash脚本一样,它是在我喝了几杯啤酒时才写的;-)

规范的答案:

[ -f $filename ] && echo "it has worked!"

或者,如果我们确实想要:

function file-exists {
    [ "" ] && [ -f  ]
}

file-exists $filename && echo "It has worked"