Search code examples
linuxbashcatstderr

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. So far i can understand and get it to work using echo but my task is to do this using cat only. 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. How can this be done using cat instead of echo? With the stderr message still being printed out as well if thats possible using only cat?

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

Solution

  • cat is used to output data from a file. To output data from a string, use echo.

    2> is for redirecting stdout to a file. To point stdout to stderr, use >&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):

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