su -c从命令内部引用参数

时间:2014-12-24 10:39:40

标签: linux bash shell ubuntu command-line

CODE

repoPath=/var/www/vhosts/www
user=www-data

showCommands=1

execCmd()
{
    local cmd="$@";

    if [ -n "$showCommands" ]; then
        log "$cmd" "CMD";
    fi

    if [ ! -n "$noExecute" ]; then
        echo "$($cmd)";
    fi
}

suCmd()
{
    echo "$(execCmd su - $user -c \"$@\")";
}

log()
{
    if [ -z $2 ]; then
        level="INFO";
    else
        level=$2;
    fi

    echo -e $(date +%F\ %T) "[$level] $1";
}

main()
{
    echo "$( suCmd git -C ${repoPath} rev-parse --abbrev-ref HEAD )";
}

main

输出

su: invalid option -- 'C'
Usage: su [options] [LOGIN]

Options:
  -c, --command COMMAND         pass COMMAND to the invoked shell
  -h, --help                    display this help message and exit
  -, -l, --login                make the shell a login shell
  -m, -p,
  --preserve-environment        do not reset environment variables, and
                                keep the same shell
  -s, --shell SHELL             use SHELL instead of the default in passwd

2014-12-24 18:32:34 [CMD] su - www-data -c "git -C /var/www/vhosts/www rev-parse --abbrev-ref HEAD" 

构建

Bash:4.3.11

Ubuntu:14.04.1

1 个答案:

答案 0 :(得分:1)

这条线搞砸了:

echo "$($cmd)";

只需将其替换为:

eval "$@";

一切正常。