What's the effective difference between redirecting to /dev/null and simply closing the stream

StackOverflow https://stackoverflow.com/questions/22353300

  •  13-06-2023
  •  | 
  •  

سؤال

Background:
I want to test some bash scripts in a modified environment with a restricted bash. In a restricted bash I am not allowed to redirect a stream to a file e.g. 2>/dev/null
I found a workaround by simply closing the stream with e.g. 2>&-

While trying here and there I found no effective difference between 2>/dev/null and 2>&-
The STDERR output is swallowed up and doesn't appear.

$ bash -c 'ls FOO'
ls: cannot access FOO: No such file or directory
$ bash -c 'ls FOO 2>/dev/null'
$ bash -rc 'ls FOO 2>/dev/null'
bash: /dev/null: restricted: cannot redirect output
$ bash -rc 'ls FOO 2>&-'
$ bash -rc 'ls FOO 2>&- ; ls BAR'
ls: cannot access BAR: No such file or directory

I guess the processing inside bash is different but that's not important to me. What IS important to me, is can the general closing instead of redirecting to /dev/null cause any problems?

هل كانت مفيدة؟

المحلول

It depends upon what the program is doing.

If you close(2) a file descriptor, then a future open(2) would re-use the same file descriptor. Also, future write(2) (without any open) would fail with EINVAL.

Most programs don't bother to check if e.g. printf(3) succeeded (in theory, they should).

If you successfully redirect to /dev/null write(2) is always successful. Read null(4).

I recommend redirecting to /dev/null when possible.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top