Bash – safely ignore: “warning: command substitution: ignored null byte in input”

bashcommand-substitutionnull

Is it possible to safely ignore the aforementioned error message? Or is it possible to remove the null byte? I tried removing it with tr but I still get the same error message.

this is my script:

#!/bin/bash                                                                     

monitordir="/home/user/Monitor/"                                                
tempdir="/home/user/tmp/"                                                       
logfile="/home/user/notifyme"                                                   

inotifywait -m -r -e create ${monitordir} |                                     
while read newfile; do                                                          
    echo "$(date +'%m-%d-%Y %r') ${newfile}" >> ${logfile};                     
    basefile=$(echo ${newfile} | cut -d" " -f1,3 --output-delimiter="" | tr -d '\n');
    cp -u ${basefile} ${tempdir};                                               
done

when I run inotify-create.sh and I create a new file in "monitordir"

I get:

[@bash]$ ./inotify-create.sh 
Setting up watches.  Beware: since -r was given, this may take a while!
Watches established.
./inotify-create.sh: line 9: warning: command substitution: ignored null byte in input

Best Answer

As for your exact question:

Can I safely ignore: “warning: … ignored null byte … ”?

The answer is yes, since you are creating the null byte with your own code.
But the real question is: Why do you need a "null byte"?

The inotifywait command will produce an output in the form of:

$dir ACTION $filename

Which, for your input, looks like this (for file hello4):

/home/user/Monitor/ CREATE hello4

The command cut will print fields 1 and 3, and using a null delimiter in --output-delimiter="" will produce an output with an embedded null, something like:

$'/home/user/Monitor/\0hello4\n'

That is not what you need, because of the added null.

The solution turns out to be very simple.
Since you are using the command read already, do this:

#!/bin/bash
monitordir="/home/user/Monitor/"
tempdir="/home/user/tmp/"
logfile="/home/user/notifyme"

inotifywait -m -r -e create ${monitordir} |
    while read dir action basefile; do
        cp -u "${dir}${basefile}" "${tempdir}";
    done

Use the default value of IFS to split on whitespace the input and just use the directory and filename to copy.