"spch2008" Everything is good. B...">

"exec not found" when using a variable in exec

I met a strange problem.

mkfifo "spch2008"
exec 100<>"spch2008"

      

Everything is good. But, when I use the variable to replace "100", an error occurs.

exec: 100: not found

PIPE_ID=100
mkfifo "spch2008"
exec ${PIPE_ID}<>"spch2008"

      

I don't know the reason. please help me, thanks.

+3


source to share


2 answers


This is because the shell does not perform variable expansion on the left side of the redirection operator. You can use a workaround:

eval exec "${PIPE_ID}"'<>"spch2008"'

      

This will force the shell to execute variable expansion by creating



eval exec 100'<>"spch2008"'

      

The inline eval

will then feed a command to the shell that will efficiently execute

exec 100<>"spch2008"

      

+3


source


I / O redirection prevents variables from specifying file descriptors, usually outside of the redirection context <>

.

Consider:



$ cat > errmsg                     # Create script
echo "$@" >&2                      # Echo arguments to standard error
$ chmod +x errmsg                  # Make it executable
$ x=2
$ ./errmsg Hi                      # Writing on standard error
Hi
$ ./errmsg Hi ${x}>&1              # Writing on standard error
Hi 2
$ ./errmsg Hi 2>&1                 # Redirect standard error to standard output
Hi
$ ./errmsg Hi 2>/dev/null          # Standard error to /dev/null
$ ./errmsg Hi ${x}>/dev/null       # Standard output to /dev/null
Hi 2
$ 

      

0


source







All Articles