0

Some of my utils functions often share the exact same initial code, that allows the function to be called with an argument or piped input:

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}"
}

Is there a technique that allows me to "reuse" or somehow source the identical portion of code into the function definition? In my example this would be:

local arg
if (( "$#" == 0 )); then
  IFS= read -r arg     
  set -- "$arg"
fi
2
  • source script_name.sh or just . script_name.sh but be careful, script will be executed while sourcing Commented Feb 9, 2021 at 11:56
  • wow, did not know you could source random snippet of code. thanks, it works. Now I have to wrap my head around the possible side effects of the fact that the script is executed while sourcing. Commented Feb 9, 2021 at 12:14

2 Answers 2

2

No, but you can make this much shorter with:

set -- "${1:-$(cat)}"
Sign up to request clarification or add additional context in comments.

Comments

1

To partial source vars and/or functions from some script use this method:

$ cat test.sh
#!/bin/bash

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

Then souce it like this:

. ./test source

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.