0

If I am using this scenario in a script:

#!/bin/bash

addvline=$(if [ "$1" ]; then echo "$1"; echo; fi)

cat << EOF
this is the first line
$addvline
this is the last line
EOF

if $1 is emty I get a blank line.
But how can I add a blank line after $1 for the case it is not emty?

So in the case running the script like:
bash script.sh hello

I would get:

this is the first line
hello

this is the last line

I tried to achieve this with using a second echo in the if statement, but the newline does not get passed.

0

2 Answers 2

1

Let if decide to set your variable content not to use command substitution.

if [ "$1" ]; then addvline=$1$'\n'; fi

Then:

#!/bin/bash
if [ "$1" ]; then addvline=$1$'\n'; fi
cat << EOF
this is the first line
$addvline
this is the last line
EOF
1

There are several solutions to this. First, let's create a variable that contains a newline to be used later (in bash):

nl=$'\n'

then it could either be used to construct the variable to be printed:

#!/bin/bash
nl=$'\n'
if [ "$1" ]; then
    addvline="$1$nl"
else
    addvline=""
fi

cat << EOF
this is the first line
$addvline
this is the last line
EOF

Or you could avoid the if entirely if you use the correct parameter expansion:

#!/bin/bash
nl=$'\n'
addvline="${1:+$1$nl}"

cat << EOF
this is the first line
$addvline
this is the last line
EOF

Or, in one simpler code:

#!/bin/bash
nl=$'\n'

cat << EOF
this is the first line
${1:+$1$nl}
this is the last line
EOF

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.