【问题标题】:How do I manipulate a string variable as it is passed to a command?如何在将字符串变量传递给命令时对其进行操作?
【发布时间】:2016-03-21 21:22:32
【问题描述】:

我有一个 URI 方案处理程序,它在被调用时执行命令。当我访问 my-type//:example.com 时,Chrome 和我的桌面环境实际上运行了这个命令:some-command %u

some-command 是我可以自定义的,%u 是一个包含字符串 my-type//:example.com 的变量。

所以实际执行的命令是:some-command my-type//:example.com

我想做的是改变%u,使其包含example.com而不是my-type//:example.com

这是怎么做到的?

【问题讨论】:

  • 您需要提供更多详细信息。这个“URI 方案处理程序”是什么?它是用什么语言编写的?这些参数是如何传递的?
  • URI 方案处理程序是我想要的任何东西。它可以是脚本、浏览器或任何应用程序。我要问的事情需要在它到达那个程序之前发生。这就是 some-command 设置的任何值。

标签: bash gnome linux-mint


【解决方案1】:

您可以在命令时使用跟随 bash 脚本并将其传递给真正的命令名称

#!/bin/bash

EXPECTED_ARGS=2
E_BADARGS=65
# Check for proper number of command line args.
if [ $# -lt $EXPECTED_ARGS ]
then
    echo "Usage: `basename $0` commmand-for-pass-uri-without-scheme uri"
    echo "Example:  `basename $0` echo my-type://example.com"
    exit $E_BADARGS
fi

COMMAND=$1
URI=$2

# extract the protocol
proto="$(echo $URI | grep :// | sed -e's,^\(.*://\).*,\1,g')"
# remove the protocol -- updated
url=$(echo $URI | sed -e s,$proto,,g)
# extract the user (if any)
user="$(echo $url | grep @ | cut -d@ -f1)"
# extract the host -- updated
host=$(echo $url | sed -e s,$user@,,g | cut -d/ -f1)
# extract the path (if any)
path="$(echo $url | grep / | cut -d/ -f2-)"

$COMMAND $url

例如将其命名为 remove-scheme-and-call-command.sh 而不是 some-command set follow remove-scheme-and-call-command some-command

不要忘记使用 chmod +x 使您的脚本可执行并添加脚本

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-02
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-05
    • 1970-01-01
    相关资源
    最近更新 更多