0

私はシェル スクリプトの構文とプロトコルにあまり詳しくありません。

私は受け入れる次の関数を書きました

  • 必須パラメータとしてのコマンド文字列
  • オプションのパラメーターとしてエラーを無視する

--

function quit {
    \rm -f "~/script.lock"
    exit
}

function abnormal_quit {
    echo $'\n'
    echo "Script Execution Terminated Abnormally.."
    echo "STATUS :: FAIL"
    quit
}

function exec_cmd {
    command="$1"
    continue_on_error="true"
    if [ -z "$2" ]; then
        continue_on_error="false"
    fi

    echo "========================================================"
    echo "Executing command :-"
    echo "$command ....."

    if ${command[@]}
    then
        echo "Command Executed successfully with return code : $?"
        echo "COMMAND - $command"
        echo "==============================================================="
        echo $'\n'
    else
        echo "Failed to execute command with return code :- $?"
        echo "COMMAND - $command"
        echo "==============================================================="
        echo $'\n'
        if [ $continue_on_error == "false" ]; then
            abnormal_quit
        fi
    fi
}

log_file="output.log"
exec_cmd "ls -lrt >> $log_file"

上記のシェルスクリプトを実行すると、次のエラーが表示されます

[root@localhost data]# sh test.sh
========================================================
Executing command :-
ls -lrt >> log.out .....
ls: >>: No such file or directory
ls: log.out: No such file or directory
Failed to execute command with return code :- 2
COMMAND - ls -lrt >> log.out
===============================================================

Script Execution Terminated Abnormally..
STATUS :: FAIL

ここでの問題は次のとおりです。シェル スクリプトは「ls -lrt >> log.out」を単一のコマンドと見なし、リダイレクトの矢印は「ls」コマンドのファイル名引数と見なされます。したがって、エラー ">>: No such file or directory" がスローされます

4

3 に答える 3

2

eval文字列内に含まれるコマンドを実行するために使用できます。これを試して:

if eval "$command"
then
于 2013-09-17T11:43:30.203 に答える
0

コマンドを実行してみてください

command=`$1`

コマンドは、スクリプトがこの行にある瞬間に実行されますが、それ以降ではなく、command変数にはこのコマンドの実行結果が保持されることに注意してください。

于 2013-09-17T11:42:36.387 に答える