如何在Bash中无需大量echo语句打印大段文本?
在Bash中简化脚本使用说明的输出方式
当然有,Bash提供了多种方式替代大量重复的echo语句,最常用且便捷的是**Here Document( heredoc)**语法,能让你直接编写多行文本内容,无需逐行调用echo。
方法1:基础Here Document实现
直接通过cat命令配合heredoc输出多行文本,格式与你想要展示的内容完全一致,代码更整洁:
function show_usage() { cat << EOF Auto generates a recipe for the day! my_script [-a][-b][-c] To create a recipe use the three options to alter the type of recipe. Options: -a: Add any extras/toppings -b: Allow experimental recipes (beta) -c: Cut out any waste. Lorem ipsum natus sit voluptatem accusantium... EOF }
这里的<< EOF表示开始读取多行内容,直到遇到单独一行的EOF为止,cat会把这段内容直接输出到标准输出。
方法2:带缩进的Here Document
如果想让函数内的文本代码保持缩进对齐,可使用<<- EOF(注意短横线),此时文本前的**制表符(Tab)**会被自动移除,输出时不会显示缩进:
function show_usage() { cat <<- EOF Auto generates a recipe for the day! my_script [-a][-b][-c] To create a recipe use the three options to alter the type of recipe. Options: -a: Add any extras/toppings -b: Allow experimental recipes (beta) -c: Cut out any waste. Lorem ipsum natus sit voluptatem accusantium... EOF }
注意:这里的缩进必须用制表符,不能用空格,否则无法移除缩进。
其他可选方式
如果偏好printf,也可以将所有内容整合到一个printf语句中,用换行符\n分隔各行:
function show_usage() { printf "%s\n" \ "Auto generates a recipe for the day!" \ "my_script [-a][-b][-c]" \ "" \ "To create a recipe use the three options to alter the type of recipe." \ "Options:" \ " -a: Add any extras/toppings" \ " -b: Allow experimental recipes (beta)" \ " -c: Cut out any waste." \ "" \ "Lorem ipsum natus sit voluptatem accusantium..." }
不过这种方式需要每行添加引号和续行符\,可读性不如heredoc,一般不推荐用于长文本。
内容的提问来源于stack exchange,提问作者CodingFrog
相关产品推荐
相关产品推荐

