首页 > 解决方案 > 如何在shell中操作&特殊字符

问题描述

我想在 shell 脚本中操作 URL。我需要用&分隔符剪切URL,并获取相应的字符串。

我尝试过example="$(cut -d'&' -f2- <<< $1)",但是当我执行此代码并尝试执行时echo $example,它想要执行$example内容。

有人能帮我吗 ?

标签: bashshellcut

解决方案


您可能只需要引用变量。

问题脚本:

#!/bin/bash
example="$(cut -d'&' -f2- <<< $1)"
echo $example

如果你通过Shellcheck运行它,你会在输出中得到这个:

example="$(cut -d'&' -f2- <<< $1)"
                              ^-- SC2086: Double quote to prevent globbing and word splitting.
echo $example
     ^-- SC2086: Double quote to prevent globbing and word splitting.

固定脚本:

#!/bin/bash
example="$(cut -d'&' -f2- <<< "$1")"
echo "$example"

推荐阅读