How do i compare if my variable holds a newline character in shell Script

為{幸葍}努か 提交于 2019-12-23 03:40:08

问题


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`

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.

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

回答1:


Empty or undefined:

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

Single newline:

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

Undefined:

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

Note, the last command is not the opposite of

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

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




回答2:


read str
if [ ${#str} -eq 0 ]       #this can been used to decide whether str is empty or not 
   then
        echo "empty"
else
    echo "not empty"
fi



回答3:


The below command will store the length of the variable in var_length.

var_length=$(echo ${#variable})

if $var_length is greater than or equal to 1, $variable is a string



来源:https://stackoverflow.com/questions/9974109/how-do-i-compare-if-my-variable-holds-a-newline-character-in-shell-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!