2011-06-27 16 views
3

我有以下bash腳本文件內的一段代碼:如何打印新行從一個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)似乎沒有工作。相反,相同的外部函數命令似乎工作正常。如何從bash函數內打印空白換行符?

回答

5

您在反引號(或$())中放入的內容將換行符轉換爲空格。您可以直接調用該函數,而不是在反引號內使用它。

換句話說,該函數實際上會生成空行,但當您在最終的echo中使用$()時,反向查詢過程會將它們轉換爲空格。

+0

我怎麼能直接調用該函數? –

+0

我想你告訴我寫下這樣的東西: 'echo -n錯誤的語法! print_correct_syntax' –

+0

這將是'echo -n'錯誤語法!' ; print_correct_syntax'。 –

2

嘗試更換:

echo Wrong Syntax! $(print_correct_syntax) 

由:

echo Wrong Syntax! "$(print_correct_syntax)" 
+0

這是否工作? –

+1

是的,它(至少在cygwin上是我的bash)。 – mouviciel

+0

我認爲這個也適用。但我更喜歡Diego Sevilla給出的更清晰的格式 –