简体   繁体   English

当使用cat未找到参数时,bash打印帮助消息

[英]Bash printing a help message when no arguments are found using cat

What im also supposed to do is if there is no arguments i am supposed to print a "help" message to the standard error device using cat. 我还应该做的是,如果没有参数,我应该使用cat将“帮助”消息打印到标准错误设备上。 So far i can understand and get it to work using echo but my task is to do this using cat only. 到目前为止,我可以理解并使用echo使其工作,但我的任务是仅使用cat来完成此操作。 When i try the line cat 2> (help message) it goes to a new line where i can type anything and causes the script to not work correctly at all the only escape being ctrl + z . 当我尝试行cat 2> (help message)它会转到新行,我可以在其中键入任何内容,并导致脚本根本无法正确运行,唯一的转义就是ctrl + z How can this be done using cat instead of echo? 如何使用cat而不是echo来完成此操作? With the stderr message still being printed out as well if thats possible using only cat? 如果仅使用cat可能仍打印出stderr消息?

Help Message 帮助信息

Usage: concat FILE ...
Description: concatenates FILE(s) to standard output separating them with divider -----.

Code

#!/bin/bash
# concat script
if [[ $@ ]]
then
        for i in "$@"
        do
         cat "$i" && echo  "-----"
        done
exit 0
else
 cat 2> "Usage: concat FILE ...
Description: concatenates FILE(s) to standard output separating them with divider -----."
exit 1
fi

cat is used to output data from a file. cat用于从文件输出数据。 To output data from a string, use echo . 要从字符串输出数据,请使用echo

2> is for redirecting stdout to a file. 2>用于将标准输出重定向到文件。 To point stdout to stderr, use >&2 . 要将stdout指向stderr,请使用>&2

In all: 在所有:

echo >&2 "Usage: concat FILE ...
Description: concatenates FILE(s) to standard output separating them with divider -----."

If you really want to avoid using the right tool for the job, you can rewrite it in terms of a here document (creating a temporary file that cat can read from): 如果您真的想避免使用正确的工具来完成工作,则可以根据here文档(创建一个cat可以读取的临时文件)将其重写:

cat << EOF >&2
Usage: concat FILE ...
Description: concatenates FILE(s) to standard output separating them with divider -----.
EOF

如果要使用cat而不是echostderr打印消息,请尝试:

cat <<< "Usage: ..." >&2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM