Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash scripting - echo only if not empty

Tags:

bash

echo

newline

Is there an option or something I can use to encapsulate echo statements so that they don't print if the line is empty?

I was thinking something like:

myecho(str){
  if [[ -z str ]]; then
    echo str
  fi
}

but I couldn't find how to pass parameters.

like image 358
user3475234 Avatar asked Jul 30 '26 08:07

user3475234


2 Answers

Arguments to functions are passed like arguments to scripts. Starting at $1 until $n

myecho(){
    if [ -n "$1" ] ; then
        echo "$@"
    fi
}

myecho ""
myecho "foo"

Using -n in a test you can verify that a string is not empty. Learn more about functions in bash: http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-8.html

like image 182
hek2mgl Avatar answered Aug 01 '26 21:08

hek2mgl


What about this?

[ -n "${STRING}" ] && echo ${STRING}

Or the complementer version:

[ -z "${STRING}" ] || echo ${STRING}

Or you can do some "echo magic":

echo -en "Some prependig text before the empty string: \""
echo -n "${STRING}"
echo -e "\" and some postfix text..."
like image 21
Swifty Avatar answered Aug 01 '26 22:08

Swifty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!