eyo*_*100 -1 scripting shell-script
考虑以下函数:
function testForBinary {
someBin=$(command -v binary)
# Test if binary is installed
if [[ -n $someBin ]]; then
installSuccess="Success"
echo ${installSuccess}
return
else
# This should never be reached
return 1
fi
}
Run Code Online (Sandbox Code Playgroud)
取自(上下文):
function installAndTestForDialog() {
# dialog allows me to create a pretty installer
# It is a required dependency since XXXXX
# Name Removed as I'm attempting modularization
# of a script from Github that's one huge Script
# See https://unix.stackexchange.com/questions/85249/why-not-use-which-what-to-use-then
local dialogBin
local updated=false
local dialogInstallSuccess
dialogBin=$(command -v dialog)
if [[ -z $dialogBin ]]; then
printf "Installing dialog... "
if [[ $updated -eq 0 ]]; then
apt-get update > /dev/null 2>&1
updated=true
fi
# Debian Based OS
apt-get -y install dialog > /dev/null 2>&1
# Test if dialog is installed to verify installation
# above was successful.
dialogBin=$(command -v dialog)
if [[ -n $dialogBin ]]; then
# I cannot get this to echo success
# if I echo from here
dialogInstallSuccess="Success"
# Moving it here doesn't help either Why??
echo ${dialogInstallSuccess}
return
else
# This should never be reached
return 1
fi
fi
}
Run Code Online (Sandbox Code Playgroud)
我试图将其installSuccess
视为布尔值,但我做错了什么。如果我像上面那样写函数,然后添加:
isInstalled=$(testForBinary)
echo "$isInstalled"
Run Code Online (Sandbox Code Playgroud)
isInstalled
返回一个空行。我知道这不是真的,因为当我command -v binary
在函数之外运行时,binary
结果的路径。
输出(上下文):
Function and Variable Output Test
=====================
# These are other tests
# I'm performing, but note
# the blank line, which should
# print Success
2.9-MODULAR
192.168.1.227
false
false
(blank line)
Run Code Online (Sandbox Code Playgroud)
这不需要像您制作的那样复杂和脆弱。
installAndTestForDialog() {
if command -v dialog &> /dev/null; then
return 0
else
apt-get update &> /dev/null
apt-get -y install dialog &> /dev/null
fi
}
Run Code Online (Sandbox Code Playgroud)
如果对话框已安装,该函数将返回 0。否则,它将尝试安装它并返回apt-get install
命令的退出代码。
正如@muru 在评论中指出的那样,这可以浓缩为:
if ! command -v dialog; then
apt-get update
apt-get install -y dialog
fi > /dev/null 2>&1
Run Code Online (Sandbox Code Playgroud)
或者只是尝试安装它而不必检查它是否已经安装:
{ apt-get update && apt-get -y --no-upgrade install dialog ;} >/dev/null 2>&1
Run Code Online (Sandbox Code Playgroud)
如果已安装,该--no-upgrade
选项将阻止dialog
升级。