bash - 在不同的函数定义中重用代码片段

问题描述

我的一些 utils 函数通常共享完全相同的初始代码,这允许使用参数或管道输入调用函数

RED=$(tput setaf 1)
YELLOW=$(tput setaf 3)
RESET=$(tput sgr0)

# -----------

function yellow {
  local arg
  if (( "$#" == 0 )); then
      IFS= read -r arg
      set -- "$arg"
  fi
  echo "${YELLOW}$1${RESET}"
}
function red {
  local arg
  if (( "$#" == 0 )); then
      IFS= read -r arg
      set -- "$arg"
  fi
  echo "${RED}$1${RESET}"
}

是否有一种技术可以让我“重用”或以某种方式将代码的相同部分引入到函数定义中? 在我的例子中,这将是:

local arg
if (( "$#" == 0 )); then
  IFS= read -r arg     
  set -- "$arg"
fi

解决方法

不,但您可以通过以下方式缩短此时间:

set -- "${1:-$(cat)}"
,

从某些脚本中获取部分源变量和/或函数,请使用以下方法:

$ cat test.sh
#!/bin/bash

test=123
mess() { echo ok; }
# Vars and functions ends here ^^
[[ $1 =~ source ]] && return
mess

然后像这样

. ./test source