【问题标题】:su -c taking arguments from command inside quotesu -c 从引号内的命令中获取参数
【发布时间】:2014-12-24 10:39:39
【问题描述】:

代码

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" 

构建

重击:4.3.11

Ubuntu:14.04.1

【问题讨论】:

  • 你为什么需要这么多echo?尝试将echo "$(command args ...)" 替换为仅command args ... 添加的每个echo 都需要您再添加一层转义特殊字符-" & `\`...
  • 需要返回输出
  • echo "$(command args ...)" & command args ... 将在屏幕上打印完全相同的内容,前提是引用正确。 (加上 stderr 处理在 echo... 方法中搞砸了。)

标签: linux bash shell ubuntu command-line


【解决方案1】:

这一行搞砸了:

echo "$($cmd)";

只需将其替换为:

eval "$@";

一切正常。

【讨论】:

    猜你喜欢
    • 2014-07-25
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-03
    • 2020-10-22
    • 1970-01-01
    相关资源
    最近更新 更多