"Ambigous Redirect" for redirecting text to a variable

I’m making a shell script to limit the amount of time someone spends on a program but it gives me these errors:

./time_limit: line 26: $Log: ambiguous redirect
./time_limit: line 16: [: root: unary operator expected

Here is the code:

config (){
ImageViewer=/ 2> /dev/null 
AllowedTime=30 #in minutes
cmd=sol #for demonstration, I use sol installed by default in Ubuntu. Set to your liking
AllowedUser=root #Set to your liking.
ImageViewer=eog #I set this to the Eye of GNOME image viewer. If no GUI or if you don't want an explosion (really?) comment out.
#If you have another desktop change to yor image viewer.
Log=/dev/null #if you want to log this, set to file of your liking
#but make sure you have write permission.

if [ $USER = $AllowedUser ]
    echo "ACSESS ALLOWED for $AllowedTime minutes."
        at now + $AllowedTime minutes <<< "killall $cmd; $ImageViewer ../files/Explode.gif"
    echo "Session 1: $date" >> $Log
echo "This UNAUTHORIZED USE has ben recorded."
echo "Violation by $USER $date" >> $Log

I ran it though ShellCheck and it seems fine. Can anyone see the problem?

Asked By: Lovecodeabc


Your config() function is never actually called in this snippet, so it will never be executed; therefore, those variables are never set. I think you meant to but accidentally put the call to config within config itself, making it an infinitely recursive function.

You need to call config, but you should also quote all your variables.

$ unset foo
$ [ $USER = $foo ]
-bash: [: jesse_b: unary operator expected
$ [ "$USER" = "$foo" ]
$ echo foo >> $foo
-bash: $foo: ambiguous redirect
$ echo foo >> "$foo"
-bash: : No such file or directory

Note that the redirection to the unset variable $foo in the example above provokes the "ambiguous redirect" error from the shell when the variable is unquoted. The solution is to make sure that the variable is set (by correctly calling config in your case), and to additionally quote all the expansions.

Setting the nounset option with set -o nounset or set -u (or adding -u option to sh / bash in the shebang) can also help identify the cases where variables are being expanded when not initialised.

Properly indenting your script would also have helped spot the problem here.

Answered By: jesse_b
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.