如何在Bash函数中打印换行符

4

我在一个bash脚本文件中有以下代码:

#! /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
#---------------------------------------------------

函数(print_correct_syntax)内的回显空字符串命令(echo "")似乎无效。相反,同样的命令在函数外部似乎可以正常工作。如何从bash函数内打印一个空的新行?

2个回答

5
你放在反引号(或$())中的内容会将换行符转换为空格。你可以直接调用函数,而不是在反引号内使用它。
换句话说,该函数实际上生成空行,但使用$()进行反引号处理时,会将它们转换为空格,以便在最终的echo中使用。

我该如何直接调用这个函数? - p.matsinopoulos
我想你是让我写类似这样的东西:echo -n 语法错误! print_correct_syntax - p.matsinopoulos
它将是 echo -n '语法错误!' ; print_correct_syntax - Diego Sevilla

2

尝试替换:

echo Wrong Syntax! $(print_correct_syntax)

by:

echo Wrong Syntax! "$(print_correct_syntax)"

1
是的,它可以(至少在我的Cygwin Bash上可以)。 - mouviciel
我认为这个也可以工作。但是我更喜欢Diego Sevilla提供的更清晰的格式。 - p.matsinopoulos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接