Shell函数用于执行命令和重定向输出

时间:2013-09-17 11:33:37

标签: shell unix

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

我写了以下接受

的功能
  • 作为mandetory参数的命令字符串
  • 将错误视为可选参数

-

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”命令的文件名参数。因此抛出错误“>>:没有这样的文件或目录”

3 个答案:

答案 0 :(得分:2)

您可以使用eval执行字符串中包含的命令。试试这个:

if eval "$command"
then

答案 1 :(得分:0)

尝试使用

执行命令
command=`$1`

请记住,在脚本处于此行的那一刻,命令将被执行,而不是更晚,command变量将保存此命令执行的结果

答案 2 :(得分:0)

由于您不熟悉语法和协议。请先了解他们。读取网络协议并不算太多。

首先 - 决定要使用的shell的类型。语法会根据此进行更改。

其次,从脚本要求,请确保使用简单的if语句检查验证您的必需参数,否则事情必然会发生故障。

无论如何,您已经将问题的答案视为eval。

相关问题