我如何比较我的变量是否在 shell 脚本中包含换行符 [英] How do i compare if my variable holds a newline character in shell Script

查看:53
本文介绍了我如何比较我的变量是否在 shell 脚本中包含换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本,其中有一行将第三行提取到我的变量中,如下所示:

I have a script in which I have a line which does put the third line fetched in my variable like this:

variable=`sed -n '3 p' /home/nmsadm/abc.txt`

所以 variable 保存了这个值,它位于 abc.txt 的第三行.在我的情况下将是单字线或空/空白线.

So variable holds this value Which is in third line of abc.txt. In my case it will be a one word line or an empty/blank line.

如何比较 shell 脚本中的变量以了解它是否为空行?echo $variable 给我一个空行.

How can I compare the variable in a shell script to know if it's an empty/blank line? echo $variable fetched me an empty line.

我需要在这里进行什么比较,以便我确定这是一条空行?像这样:

What is the comparison i need to here so that I am assured it's an empty line? Something like this:

if [ "$variable" = "comparison" ]; then

推荐答案

空或未定义:

if [ -z "${variable-}" ]

单个换行符:

if [ "${variable-}" = $'\n' ]

未定义:

if [ "${variable+defined}" != defined ]

注意,最后一个命令不是

if [ "${variable-undefined}" = undefined ]

要了解原因,请先尝试运行 variable=undefined."${variable+defined}" 只有两个可能的值:空字符串或 defined.

To see why, try running variable=undefined first. "${variable+defined}" has only two possible values: The empty string or defined.

这篇关于我如何比较我的变量是否在 shell 脚本中包含换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆