2016-05-04 52 views
1

我参加了一门Linux课程,我们讨论的是bash脚本。以下脚本应该使用字符串值打印回显语句,但不会。

#/bin/bash 

echo "Enter the first string" 
read str1 
echo "Enter the second string" 
read str2 
echo $str1 
echo $str2 
myLen1=${#str1} 
myLen2=${#str2} 

if [ ! -z $str1 ]; then 
    echo Length of the first string is: $myLen1 
else 
    echo Please enter a value for ${str1} with more than 0 characters 
fi 

if [ ! -z $str2 ]; then 
    echo Length of the second string is: $myLen2 
else 
    echo Please enter a value for $str2 with more than 0 characters 
fi 

我曾尝试没有成功如下:

echo Please enter a value for ${str2} with more than 0 characters 

echo Please enter a value for "$str2" with more than 0 characters 

echo "Please enter a value for $str2 with more than 0 characters" 

echo "Please enter a value for ${str2} with more than 0 characters" 

任何想法?

+1

该字符串有0个字符。你打算什么时候看到它? –

+0

@EtanReisner这很有道理。显然,没有东西会打印。我很抱歉。相反,我只是附加它们来说'回声'条目1:...“'和'回声”条目2:...“' – Debug255

+1

添加'set -vx'来启用shell调试/跟踪功能。然后你可以在执行代码之前看到每一行代码,然后该行以'+'开始,并且所有变量替换都已就绪。然后你就可以理解你的代码正在发生什么。顺便说一句,'set -v'部分实际上处理代码块,所以它会打印出一个巨大的while循环,然后只有'+'行被实际执行。它可能会令人困惑,究竟哪一行正在执行。添加'export PS3 ='$ LINENO>''来查看正在执行的代码的行数。祝你好运。 – shellter

回答

2

你说你是在一个涵盖bash的Linux课程。因此,我将分享,我希望会帮助你通常一些一般性意见:

测试和调试
启动bash脚本bash -x ./script.sh或脚本set -x添加看到调试输出。

语法
作为@drewyupdrew指出的还有,你需要像脚本的顶部指定你使用的shell:#!/bin/bash(您缺少!)。

您在[ ! -z $str2 ]中使用-z比较运算符。 -z运算符比较字符串是否为空,即长度为零。您正在否定与!的比较。

执行此相同操作的更简洁的方法是使用-n比较运算符。 -n运算符测试字符串是否不为空。

此外,重要的是必须引用测试括号中的变量,即单个[ ] s。然而,使用带有! -z的未加引号的字符串,或者仅在测试括号内单独使用未加引号的字符串通常可行,但这是一种不安全的做法。

因此,采取上述笔记考虑,与其他几个编辑一起,我想出了以下内容:

#!/bin/bash 

echo "Enter the first string" 
read str1 
echo "Enter the second string" 
read str2 

echo "This is the first string: ${str1}" 
echo "This is the second string: ${str2}" 

myLen1=${#str1} 
myLen2=${#str2} 

if [ -n "$str1" ]; then 
    echo "Length of the first string is: ${myLen1}" 
else 
    echo "Please enter a value for the first string with more than 0 characters" 
fi 

if [ -n "$str2" ]; then 
    echo "Length of the second string is: ${myLen2}" 
else 
    echo "Please enter a value for the second string with more than 0 characters" 
fi 

这是否帮助?

+0

马克米切尔是的,非常有帮助。我正在学习的课程在edx.org上,实验结果或答案显示了单个括号,并且'! -z $ str1'。我想我没有注意到'#/ bin/bash'问题,因为我正在执行脚本为'bash script.sh'。感谢您的洞察,因为它效果更好。 – Debug255

0

在您尝试打印输入的脚本部分中,您刚刚断言输入不包含任何字符。因此,当变量扩展时,它会扩展为空字符串,并且您看不到任何内容。