繁体   English   中英

bash脚本在echo语句中不显示$ strings

[英]bash script does not display $strings in echo statements

我正在学习Linux课程,我们将介绍bash脚本。 以下脚本应使用字符串值打印echo语句,但不会。

#/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"

有任何想法吗?

您说您正在学习有关bash的Linux课程。 因此,我将分享一些一般性意见,希望对您有整体帮助:

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

句法
正如@drewyupdrew所指出的那样,您需要在脚本顶部指定要使用的shell,例如: #!/bin/bash (您缺少 )。

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

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

另外,重要的是必须在测试括号中的变量(即单个[ ]加引号。 ! -z使用无引号的字符串! -z ! -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

有帮助吗?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM