p.matsinopoulos
p.matsinopoulos

Reputation: 7810

How can I print a newline from within a bash function

I have the following piece of code inside a bash script file:

#! /bin/sh
#
# Usage:
#
# f.sh <start_directory> <destination_directory> <prepare_directory> <remote_host_for_copy> <remote_user>
#
print_correct_syntax() {

 echo "f.sh <start_directory> <destination_directory> <prepare_directory> <remote_host_for_copy> <remote_user>"
 echo ""
 echo '<start_directory> needs to be a full path, <destination_directory> needs to be full path, <prepare_directory> has to be relative to start_directory path'
 echo ""

}
# ---- end of function definition ----

# check number of run-time arguments given to script

if [ $# != 5 ]
then
 echo Wrong Syntax! $(print_correct_syntax)
 exit;
fi
#---------------------------------------------------

The echo empty string commands (echo "") inside the function (print_correct_syntax) do not seem to be working. On the contrary, same commands outside function seem to be working fine. How can I print an empty newline from within a bash function?

Upvotes: 4

Views: 3408

Answers (2)

mouviciel
mouviciel

Reputation: 67929

Try to replace:

echo Wrong Syntax! $(print_correct_syntax)

by:

echo Wrong Syntax! "$(print_correct_syntax)"

Upvotes: 2

Diego Sevilla
Diego Sevilla

Reputation: 29019

What you put in backquotes (or $()) gets the newlines translated into spaces. You can directly call the function instead of using it inside backquotes.

In other words, the function actually generates the empty lines, but the backquoting process with $() translates them into spaces when you use it in your final echo.

Upvotes: 5

Related Questions