@Barmar 是对的,“当您获取每个文件时,它的功能会替换前一个。”
对于任何对这个问题的目的感兴趣的人,我的目标是在这个 bash 脚本中获得某种面向对象的理智:
switch1.sh
switch()
{
echo "switch1"
}
check_administratorpassword()
{
file="switch1.sh"
description="Administrator password required to change system-wide preferences"
switch=$(switch)
if [ -n "$(security authorizationdb read system.preferences 2> /dev/null | grep -A1 shared | grep -E '(true|false)' | grep 'false')" ]; then
return 0
else
return 1
fi
}
switch2.sh
switch()
{
echo "switch2"
if which brew > /dev/null; then
read -p "Check for Homebrew updates? (y/n): " input
if [[ $input == "Y" || $input == "y" ]]; then
echo "Checking for Homebrew updates..."
brew update
elif [[ $input == "N" || $input == "n" ]]; then
:
else
echo "Not a recognized input."
switch_homebrewinstall
fi
else
echo "Homebrew is not installed."
read -p "Install Homebrew? (y/n): " input
if [[ $input == "Y" || $input == "y" ]]; then
# Install Homebrew, TODO: Find secure way to download homebrew
echo -e "Installing Homebrew..."
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
elif [[ $input == "N" || $input == "n" ]]; then
:
else
echo "Not a recognized input."
switch_homebrewinstall
fi
fi
unset input
}
check_homebrewinstall()
{
file="switch2.sh"
description="Homebrew is installed."
switch=$(switch)
if which brew > /dev/null; then
return 0
else
return 1
fi
}
switch3.sh
switch()
{
echo "switch3"
}
check_javainstall()
{
file="switch3.sh"
description="Java is installed."
switch=$(switch)
path=$(type -p java)
if [[ $path = /dev/null ]]; then
return 1
else
return 0
fi
unset path
}
switch-test.sh
source switch1.sh
source switch2.sh
source switch3.sh
declare -a checkArray
checkArray[1]=check_administratorpassword
checkArray[2]=check_homebrewinstall
checkArray[3]=check_javainstall
for i in "${!checkArray[@]}"; do
${checkArray[$i]}
if [ $? -eq 1 ]; then
echo -e "\xE2\x9C\x97 ${description}"
else
echo -e "\xE2\x9C\x93 ${description}"
fi
source "${file}"
switch
done
输出
$ bash switch-test.sh
✗ Administrator password required to change system-wide preferences
switch1
✓ Homebrew is installed.
switch2
✓ Java is installed.
switch3
这个文件是在 switch 函数被调用之前重新获取资源的,给人一种奇怪的错觉,认为它是 OOP。我不建议这样做,因为没有人查看您的代码会认为这是正在发生的事情,但它有点酷。