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

时间:2011-06-27 09:23:23

标签: bash debian newline echo

我在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空字符串命令(echo“”)似乎不起作用。相反,函数外的相同命令似乎工作正常。如何在bash函数中打印空换行?

2 个答案:

答案 0 :(得分:5)

您在反引号(或$())中放置的内容会将换行符转换为空格。您可以直接调用该函数,而不是在反引号中使用它。

换句话说,该函数实际上会生成空行,但是当您在最终的$()中使用它时,带有echo的反引号过程会将它们转换为空格。

答案 1 :(得分:2)

尝试替换:

echo Wrong Syntax! $(print_correct_syntax)

由:

echo Wrong Syntax! "$(print_correct_syntax)"