【问题标题】:Conditionally exclude echo statements in ksh有条件地排除 ksh 中的 echo 语句
【发布时间】:2014-01-25 03:46:43
【问题描述】:
我想在我的 KornShell (ksh) 脚本中设置详细/非详细模式。
详细地说,我需要用
执行语句
echo blah blah blah
但在非冗长的情况下,我不想排除那些 echo 语句
现在我猜测有一种更好/优雅的方法来实现这一点,而不是使用全局的冗长状态并做一个
if [[ $verbose eq 1 ]] ; then
echo blah blah blah
fi
我是 ksh 新手,不知道所有技巧。
有人会建议可以做什么吗?
【问题讨论】:
标签:
shell
scripting
echo
ksh
【解决方案1】:
事不宜迟(在 ksh 和 bash 中有效,而不是 POSIX sh):
# function verbose()
# accepts on | off | an empty string | a message
# on|off changes the global variable _Verbose
# Anything else will return the value of ${_Verbose}
# and (optionally) display a message (which cannot start with on or off)
#
# Use only as conditional for echo: verbose && echo ...
_Verbose=0
verbose() {
case ${1} in
(on) _Verbose=1;;
(off) _Verbose=0;;
("") ((_Verbose));;
(*) ((_Verbose)) && echo "$*"
esac
}
$ verbose on
$ verbose && echo "Here's a message"
Here's a message
$ verbose "And another one"
And another one
$
$ verbose off
$ verbose && echo "Here's a message"
$ verbose "And another one"
【解决方案2】:
这应该只适用于 ksh、bash 或任何 POSIX 或 bourne shell 衍生物:
$ debug=true
$ $debug && echo blah blah blah
blah blah blah
$ debug=false
$ $debug && echo blah blah blah
$
【解决方案3】:
哎呀,你说的是“ksh”,但这个概念很相似......
你可以这样做:
export DEBUG=1
[ $DEBUG -eq 1 ] && echo hi
hi
export DEBUG=0
[ $DEBUG -eq 1 ] && echo hi
或者您可以使用“-xv”标志执行脚本,方法是更改开头的 shebang 行
#!/bin/bash -xv
Line 1 of your script...
Line 2 of your script
或者通过执行这样的脚本:
bash -xv yourscript
或者,您可以在您的登录/配置文件脚本中定义一个 debug() 函数并在那里进行检查。