user9475900
user9475900

Reputation:

How to make a pipeable bash script

I am working on a bash package called Tools, and I am trying to make a bash script that you can pipe trough to pass all output of a command to /dev/null.

Example:

cat myfile | null

null being the command in Tools.

And then it would output nothing. I know how to redirect output to /dev/null or other places, but, how do I make a pipe-able script to do that.

My current placeholder code:

#!/bin/bash
sudo $1 &> /dev/null

Execution format:

null cat\ myfile 

The backslash is an escape character so that bash knows that it is one argument, not two; Arguments are usually separated by spaces

Upvotes: 1

Views: 937

Answers (2)

Jens
Jens

Reputation: 72639

Too many useless uses of cats here. All your script needs to do is

exec >/dev/null

And if you want to nuke stderr as well,

exec >/dev/null 2>/dev/null

Note that exec without a command makes its redirections apply for the remainder of the script.

Upvotes: 1

larsks
larsks

Reputation: 311606

For this to work:

somecommand | null

You would just need your null script to contain:

cat > /dev/null

cat reads from stdin and writes to stdout, which in this case you have redirected to /dev/null.

Note that this will not redirect stderr, because the pipe symbol (|) only redirects stdout. You can use |& to redirect both stdout and stderr, as in:

somecommand |& null

The real question, though, is why bother with this? You can just as easily run:

somecommand > /dev/null

Or:

somecommand >& /dev/null

UPDATE

Wow, bash 3.2? That's too old. That version of bash doesn't have support for the |& operator. You can accomplish the same thing like this:

somecommand 2>&1 | null

That says "redirect stderr to stdout, and then redirect stdout to a pipe".

Upvotes: 4

Related Questions