Linux教程 - 在Shell脚本中声明和使用布尔变量示例
Posted Linux公社
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Linux教程 - 在Shell脚本中声明和使用布尔变量示例相关的知识,希望对你有一定的参考价值。
jobdone=1 # True
## 更具可读性的语法 ##
failed=false
jobdone=true
if [ $failed -eq 1 ]
then
echo "Job failed"
else
echo "Job done"
fi
就这样。
如何在Shell脚本中声明和使用布尔变量(例如“ true”和“ false”)
当然,我们可以将它们定义为字符串,并使我们的代码更具可读性:
#!/bin/bash
# Declare it as string
failed="false"
if [ "$failed" == "true" ]
then
echo "Job failed"
else
echo "Job done"
fi
或者
# set it to true
email_sent=true
# ...do your stuff and flip email_sent to 'false' if needed ...
if [ "$email_sent" = true ]
then
echo 'Data logged and email sent too.'
else
echo 'ALERT: Operation failed.'
logger 'ALERT: Operation failed.'
fi
# Let us Declare Two Boolean Variables
# Set this one to true
jobstatus=true
# Check it
if [ "$jobstatus" = true ] ; then
echo 'Okay :)'
else
echo 'Noop :('
fi
# Double bracket format syntax to test Boolean variables in bash
bool=false
if [[ "$bool" = true ]] ; then
echo 'Done.'
else
echo 'Failed.'
fi
#!/bin/bash
# Purpose: Backup stuff from /data/apps
# Tested on : AWS EC2 with EFS and Ubuntu 20.04 Pro servers
# ---------------------------------------------------------
source "/apps/.keychain/$HOSTNAME-sh"
source "/apps/scripts/cli_app.sh"
# Set failed to 'False'
failed=0
D="/nfsefs/ec2mum/prodwwwroot"
log="/tmp/server.log.$$.txt"
# Log everything to our file
exec 3>&1 4>&2
trap 'exec 2>&4 1>&3' 0 1 2 3
exec 1>"${log}" 2>&1
# Backup all web servers
for s in www-0{1..8}
do
/usr/bin/rsync -az --delete backupt@${s}:/data/apps/ ${D}/${s}/
# set to 'true' when rsync failed and continue loop
[ $? -ne 0 ] && failed=1
done
# See if rsync failed in loop
if [ $failed -eq 1 ]
then
echo "$0 script error: rsync backup failed. See attached log file." | mail -A ${log} -s "$HOSTNAME - LXD backup failed" -r sysuser@my-corp-tld alert@somewhere-tld
push_to_mobile "$0" "Dear sysadmin,
Backup failed at $HOSTNAME at $(date).
---- log:start ---
$(<${log})
--- log:end --
--
Yours faithfully,
$0"
fi
[ -f "${log}" ] && rm -f "${log}"
if [ $status -ne 0 ] || [ "$alogs" != "" ]; then
sub="Backup job failed at $HOSTNAME"
mail -A "$log" -s "$sub" -r sys@somewhere-tld sysadmin@gmail-tld <<< "$0 script ended with errors when we ran /usr/bin/rsnapshot \"$1\" $alogs"
push_to_mobile "$0" "$sub
$0 script ended with errors when we ran /usr/bin/rsnapshot \"$1\"
$alogs
See email for detailed log."
else
sub="Backup successful at $HOSTNAME"
#push_to_mobile "$0" "$sub. See email for detailed backup log." >/dev/null
#mail -A "$log" -s "$sub" -r sys@somewhere-tld sysadmin@gmail-tld <<< "$0 /usr/bin/rsnapshot ran successfully\"$1\" $alogs"
fi
$ help test
$ help if
...END...
长按或扫描下面的二维码关注Linux公社
关注Linux公社,添加“星标”
每天获取技术干货,让我们一起成长
合作联系微信:linuxgs
以上是关于Linux教程 - 在Shell脚本中声明和使用布尔变量示例的主要内容,如果未能解决你的问题,请参考以下文章
Linux系列教程(二十)——Linux的shell概述以及如何执行脚本