“Ambigous Redirect”用于将文本重定向到变量

“Ambigous Redirect”用于将文本重定向到变量

我正在制作一个 shell 脚本来限制某人在程序上花费的时间,但它给了我以下错误:

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

这是代码:

#!/bin/bash
config (){
ImageViewer=/ 2> /dev/null 
AllowedTime=30 #in minutes
AllowedPlays=1
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.
config
date=$(date)

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

我通过 ShellCheck 运行了它,看起来不错。任何人都可以看到问题吗?

答案1

您的config()函数从未在此代码段中实际调用,因此它永远不会被执行;因此,这些变量永远不会被设置。我认为您本想但不小心将调用放入其自身config内部config,使其成为无限递归函数。

您需要调用config,但您还应该引用所有变量。

$ 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

$foo请注意,当变量未加引号时,重定向到上例中未设置的变量会引发 shell 中的“不明确重定向”错误。解决方案是确保设置变量(通过config在您的情况下正确调用),并另外引用所有扩展。

使用or设置nounset选项(或在 shebang 中向/添加选项)还可以帮助识别变量在未初始化时扩展的情况。set -o nounsetset -u-ushbash

正确缩进脚本也有助于发现这里的问题。

相关内容