如何操作 shell 中的 & 特殊字符

How to manipulate the & special character in shell

我想在 shell 脚本中操作 URLs。我需要用&分隔符切割URL,并得到相应的字符串。

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

有人可以帮助我吗?

不,不是。

当你这样做时:

example="$(cut -d'&' -f2- <<< )"

它尝试执行 cut。作为测试:

ljm@verlaine[~]$ a='1&ls&3&4'
ljm@verlaine[~]$ example="$(cut -d'&' -f2- <<< $a)"
ljm@verlaine[~]$ echo $example
ls&3&4
ljm@verlaine[~]$ 

而且,虽然像 iBug 建议的那样引用是一个好主意和最佳实践,但这里并不是绝对需要的。

您可能只需要引用变量。

问题脚本:

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

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

example="$(cut -d'&' -f2- <<< )"
                              ^-- 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- <<< "")"
echo "$example"