Score:0

cat : Do not read stdin if no input file is given on the command line

ph flag

I have a script that concatenates files with cat. It contains roughly the following line that hangs the script in reading the standard input if the directory contains no files:

cat /path/to/dir/* > concat.txt

Is there a way to either make cat not read anything from standard input and produce an empty output if no files exist at /path/to/dir/, or use another command to achieve the same?

raj avatar
cn flag
raj
In your case, if no files exist at `/path/to/dir/*`, `cat` will display an error message and not read anything from stdin. Have you actually tried it? `cat` reads from stdin only if there is **no parameter present**, not if there **is** a parameter that specifies a non-existent file.
Score:3
us flag

It seems you have nullglob enabled so that /path/to/dir/* expands to nothing if no files are present in /path/to/dir/. You could, of course, disable nullglob (shopt -u nullglob) and get the default behaviour, where /path/to/dir/* remains as-is if nothing matches and cat will complain about the non-existent file:

$ cat /path/to/dir/*
cat: '/path/to/dir/*': No such file or directory

You could also just tack on a /dev/null at the end instead:

$ shopt -s nullglob; cat /path/to/dir/* /dev/null
$ echo $?
0

cat will get an immediate EOF from /dev/null, so it will write nothing and quit.

Serge Rogatch avatar
ph flag
Thanks, `/dev/null` idea is especially attracting.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.