我试图将我的脚本分解为较小的部分,以使其更有条理和可读。
我想使用一些代码(其中包含一个时循环,可变分配和用户输入(,然后将此代码放入另一个文件中。以下是我的代码的示例。它的性能完全尽可能。
脚本
var1="hello"
var2="world"
echo "Defaults: Var1(a)-$var1 Var2(b)-$var2"
read -p "Change Defaults? ";
while [ $REPLY != "n" ]
do
if [ $REPLY == "a" ]
then
read -p "Var1 = "
var1=$REPLY
elif [ $REPLY == "b" ]
then
read -p "Var2 = "
var2=$REPLY
fi
read -p "Change Defaults? ";
done
echo "$var1 $var2"
我希望我的脚本执行相同的脚本,但看起来不同,并且结构不同
我希望脚本看起来像
var1="hello"
var2="world"
echo "Defaults: Var1(a)-$var1 Var2(b)-$var2"
cmd=$(cat other_file.txt)
eval $cmd
echo "$var1 $var2"
其中其他_file.txt包含
read -p "Change Defaults? ";
while [ $REPLY != "n" ]
do
if [ $REPLY == "a" ]
then
read -p "Var1 = "
var1=$REPLY
elif [ $REPLY == "b" ]
then
read -p "Var2 = "
var2=$REPLY
fi
read -p "Change Defaults? ";
done
使用 .
(aka source
(导入函数定义。
other_file.bash
将包含(有一些改进(
foo () {
local REPLY
read -p "Change Defaults? "
while [[ $REPLY != n ]]
do
if [[ $REPLY == a ]]
then
read -p "Var1 = " var1
elif [[ $REPLY == b ]]
then
read -p "Var2 = " var2
fi
read -p "Change Defaults? "
done
}
和您的脚本:
. otherfile.bash
var1="hello"
var2="world"
echo "Defaults: Var1(a)-$var1 Var2(b)-$var2"
foo
echo "$var1 $var2"
从函数中移动通用代码开始。当功能正常工作时,您可以将其移至Incluber文件。我的名字"包括",因为看起来像其他语言。
其他文件也可以包含一个包含文件,因此请确保您在"部署"到Include File之前已经对您的函数进行了很好的测试。
可以通过对其进行采购(使用. includefile
的source includefile
(来包括其中的文件。您可能需要设置一个仅包含文件的文件夹。我有一个带有bin
,shlib
,config
和sql
的项目。shlib
文件夹都包含文件。当您发挥功能时,您可以花更多的时间在其中。我会用
changevars() {
if [ $# -eq 0 ]; then
echo "${FUNCNAME} should be called with at least 1 argument"
return
fi
PS3="Change Defaults (n to quit)?"
select opt in "$@"
do
if [[ $REPLY = n ]]; then
break;
fi
[[ $REPLY =~ ^[0-9]+$ ]] && [ $REPLY -le $# ] &&
read -p "$opt (${!opt}) = " ${opt}
done
}
并用
调用此功能source yourpath/shlib/util.sh
var1="hello"
var2="world"
echo "Defaults: Var1(a)-$var1 Var2(b)-$var2"
changevars var1 var2
echo "$var1 $var2"