I have some command lines stored in a text file, and I separated them into different groups by using distinguished row symbol, say #step1 for group one, #step2 for group two,etc. My question is how I'm able to extract each group and execute each command line by using #step* as an input argument.
steps text file:
#step1
command line 1
command line 2
command line 3
...
#step2
command line 4
command line 5
command line 6
...
How to create a function somewhere in my code context, which can do something like:
execSteps "#step1"
or is there another way to organize my steps text file?
Any ideas?
Thank you very much!
One approach:
getSteps() {
local running=0
while read -r line; do
if (( running )); then
if [[ $line = "#"* ]]; then
return
else
printf '%s\n' "$line"
fi
else
[[ $line = "#"$1 ]] && running=1
fi
done <stepFile
}
execSteps() {
getSteps "$@" | sh -
}
Then, you can print the code for a step by running getSteps step1
, or execute that code with execSteps step1
.
It sounds like you just want to define a shell "module". Save it as mymodule
:
step1 () {
command line 1
command line 2
command line 3
}
step2 () {
command line 4
command line 5
command line 6
}
To use it, simply source it from your script, and call the desired function
. mymodule
# Run step 1
step1
# Run step 2