「あいまいなリダイレクト」は、テキストを変数にリダイレクトするために使用されます。

「あいまいなリダイレクト」は、テキストを変数にリダイレクトするために使用されます。

誰かがプログラムに費やす時間を制限するためにシェルスクリプトを作成していますが、次のエラーが発生します。

./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上記の例で設定されていない変数にリダイレクトすると、変数が引用されていない場合、シェルで「あいまいなリダイレクト」エラーが発生します。回避策は、変数が設定されていることを確認し(configあなたの場合は正しく呼び出して)、すべての拡張子を参照することです。

あるいは、オプションを設定することnounset(またはshebangから/にオプションを追加すること)は、初期化されていないときに変数が拡張される状況を識別するのに役立ちます。set -o nounsetset -u-ushbash

スクリプトを適切にインデントすることも、ここで問題を特定するのに役立ちます。

おすすめ記事