help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Redirecting error message from ${parameter:?word}


From: Andreas Kusalananda Kähäri
Subject: Re: Redirecting error message from ${parameter:?word}
Date: Sat, 11 Jan 2020 23:33:17 +0100

On Sat, Jan 11, 2020 at 10:33:13PM +0100, Michael Siegel wrote:
> Why is it, apparently, not possible to redirect an error message from a
> ${parameter:?word} expansion to /dev/null within the same shell instance?
> 
> Here's some code to demonstrate what I mean:
> 
> $ echo "$BASH_VERSION"
> 4.4.12(1)-release
> $ name=Max
> $ printf 'Hello, %s.\n' "${name:?}"
> Hello, Max.
> $ name=
> $ printf 'Hello, %s.\n' "${name:?}"
> bash: name: parameter null or not set
> $ printf 'Hello, %s.\n' "${name:?}" 2>/dev/null
> bash: name: parameter null or not set
> $ cat test
> #!/bin/bash
> 
> name="$1"
> 
> printf 'Hello, %s.\n' "${name:?}" 2>/dev/null
> printf 'Bye\n'
> $ ./test Max
> Hello, Max.
> Bye
> $ ./test
> ./test: line 5: name: parameter null or not set
> $ ./test 2>/dev/null
> $
> 
> 
> --Michael

Because it's the shell that produces the diagnostic message, not the
printf command.  Redirecting the printf command's error stream will not
do anything.

To redirect the diagnostic message, you would have te redirect the
shell's error stream.  You can do that by, for example, placing the
printf in a subshell and redirecting that subshell's error stream:

$ ( printf 'Hello, %s.\n' "${name:?}" ) 2>/dev/null
$

This is also equivalent to what happens in your second example where you
redirect the script's error stream.

Regards,

-- 
Andreas (Kusalananda) Kähäri
SciLifeLab, NBIS, ICM
Uppsala University, Sweden



reply via email to

[Prev in Thread] Current Thread [Next in Thread]