0

我对 shell 脚本语法和协议不太熟悉。

我写了以下接受的函数

  • 命令字符串作为强制参数
  • 忽略错误作为可选参数

--

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"

如果我执行上面的 shell 脚本,它会给我以下错误

[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

这里的问题是 - shell 脚本将“ls -lrt >> log.out”假定为单个命令,并且重定向箭头被视为“ls”命令的文件名参数。因此抛出错误“>>:没有这样的文件或目录”

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 回答
0

由于您不熟悉语法和协议。请先了解他们。像网络协议一样阅读并不过分。

首先 - 决定您要使用的外壳类型。语法会基于此进行更改。

其次,从脚本要求来看,确保您使用简单的 if 语句检查来验证您的强制参数,否则事情肯定会失败。

无论如何,您已经有了 eval 问题的答案。

于 2013-09-17T21:18:23.900 回答