【发布时间】:2015-11-09 13:27:04
【问题描述】:
所以我对 bash 很陌生,我只是编写一个基本脚本来为我运行一个应用程序实用程序。然后我想要检查特定字符串响应的输出并记录它是否有错误。现在,如果我只使用这一行,我就可以让脚本正常工作
if [[ $condition == *"added"* ]] ; then
当我试图寻找一个精确的比较时
if [[ "$condition" == "CONDITION:${2} DATE:${3} added" ]] ; then
即使从我看到的输出是正确的,它也不起作用。我有一种感觉,我比较错误或添加了一些秘密字符,这是我尚未学习的 bash 功能。任何帮助将不胜感激。
更新!
因此,根据我收到的反馈,我试图让我的代码更清晰,并了解原始字符串值是什么。到目前为止,感谢大家的回复。以下是更新后的脚本和输出
#!/usr/bin/sh
# This script posts a condition sent to it by the Shout Destination table
# in CCM. Used to generate JOB_LATE incidents.
# If an error is encountered it is logged in the
# job_late_error_log.txt file.
# utility -> ctmcontb -ADD <Condition Name> <Condition Date>
# Condition format -> L@%%JOBNAME-%%NODEID -> JOB_LATE format
# $2 = L@%%JOBNAME-%%NODEID $3 = <Condition Date>
cmd_output=$(ctmcontb -ADD $2 $3)
time_stamp=$(date)
working_directory=/apps/ctm/devsv/scriptsadmin/do_condition/
error_file=job_late_error_log.txt
write_file_to_location=$working_directory$error_file
#if [[ $cmd_output == *"added"* ]] ; then
echo below is the hex output of "CONDITION:${2} DATE:${3} added"
echo "CONDITION:${2} DATE:${3} added" | od -xc
echo below is the command for $cmd_output
echo "$cmd_output" | od -xc
cmd_ouput_no_space = "$(echo -e "${cmd_output}" | tr -d '[[:space:]]')"
echo below is the command with white spaces removed
echo $cmd_ouput_no_space
if [[ "$cmd_ouput_no_space" == "CONDITION:${2} DATE:${3} added" ]] ; then
echo $cmd_ouput_no_space
echo successfull ran util
exit 0
else
# echo $cmd_ouput_no_space $time_stamp >> $write_file_to_location
echo $cmd_ouput_no_space
echo error occurred running util
exit 1
fi
和输出:
ctmtest1-tctmsv80 [9] job_late.sh ctmtest1 u350932-test2 0816
below is the hex output of CONDITION:u350932-test2 DATE:0816 added
0000000 434f 4e44 4954 494f 4e3a 7533 3530 3933
C O N D I T I O N : u 3 5 0 9 3
0000020 322d 7465 7374 3220 4441 5445 3a30 3831
2 - t e s t 2 D A T E : 0 8 1
0000040 3620 6164 6465 640a
6 a d d e d \n
0000050
below is the command for CONDITION:u350932-test2 DATE:0816 added
0000000 2043 4f4e 4449 5449 4f4e 3a75 3335 3039
C O N D I T I O N : u 3 5 0 9
0000020 3332 2d74 6573 7432 2044 4154 453a 3038
3 2 - t e s t 2 D A T E : 0 8
0000040 3136 2061 6464 6564 0a00
1 6 a d d e d \n
0000051
job_late.sh[19]: cmd_ouput_no_space: not found
below is the command with white spaces removed
error occurred running util
我不熟悉 od -xc 调用,但看起来我的价值观不同,这是有道理的。不知道为什么?
更新 2:
所以我尝试使用 line 删除所有空格
cmd_ouput_no_space = "$(echo -e "${cmd_output}" | tr -d '[[:space:]]')"
我在这里找到的:
How to trim whitespace from a Bash variable?
但它似乎不起作用。我已经更新了我的原始脚本,并在这篇文章的顶部输出了我遇到的错误。
【问题讨论】:
-
查看输出的十六进制转储。例如,
job_late.sh ctm... | xxd -
请以十六进制显示
$condition。您可以使用:echo "$condition"|od -xc。确保"$condition"在此处的双引号内,否则我们将错过额外的空格。除了@JohnathanLeffler 已删除的帖子,请澄清您的输出。 -
您是否使用
source或点 (.) 命令“采购”此脚本?如果不是,那么return语句无效 - 它们只能在源文件或函数中使用。你的意思可能是exit。