强制转换字符串以不允许在 shell 脚本中的函数内进行插值
Casting a string to not allow for interpolation within a function in shell script
我正在寻找某种方法来在传递给 shell 中的程序的字符串中打印星号。这些问题很相似,但我无法使任何解决方案适用于我的情况:how do I echo an asterisks to an output, Printing asterisk (*) in bash shell, How do I escape the wildcard/asterisk character in bash?.
我有以下脚本:
#!/bin/bash
# First function
function()
{
typeset -r str=
typeset -i N=
typeset -i i=0
while [[ $i -lt $N ]];
do
echo $str| sed "s/<token>/$i/g"
(( i+=1 ))
done
}
# 'main' function
doStuff()
{
foo.pl << EOF
some words $(function "input string with asterisk * and some <token> after it" 123)
some more words
EOF
[ $? -eq 0 ] || logerror "Function 'doStuff' failed."
}
doStuff
exit 0
当运行脚本时,星号被echo *
的结果代替。
为了解决这个问题,我尝试声明 ASTERISK='*'
并将其替换,以及简单地将函数调用更改为 $(function "input string with asterisk "'*'" and some <token> after it" 123)
,但都没有成功。
我怀疑问题出在function
中的echo
语句,但我不太确定如何解决它,所以我的问题是是否有任何方法可以转换str
在 function
中不允许在 function
内进行插值?
您可以用 ""
包围变量扩展以避免 glob。
echo "$str" | ...
根据 arco444 的建议,在 function
中的 sed
之前使用 set -o noglob
就成功了。
我正在寻找某种方法来在传递给 shell 中的程序的字符串中打印星号。这些问题很相似,但我无法使任何解决方案适用于我的情况:how do I echo an asterisks to an output, Printing asterisk (*) in bash shell, How do I escape the wildcard/asterisk character in bash?.
我有以下脚本:
#!/bin/bash
# First function
function()
{
typeset -r str=
typeset -i N=
typeset -i i=0
while [[ $i -lt $N ]];
do
echo $str| sed "s/<token>/$i/g"
(( i+=1 ))
done
}
# 'main' function
doStuff()
{
foo.pl << EOF
some words $(function "input string with asterisk * and some <token> after it" 123)
some more words
EOF
[ $? -eq 0 ] || logerror "Function 'doStuff' failed."
}
doStuff
exit 0
当运行脚本时,星号被echo *
的结果代替。
为了解决这个问题,我尝试声明 ASTERISK='*'
并将其替换,以及简单地将函数调用更改为 $(function "input string with asterisk "'*'" and some <token> after it" 123)
,但都没有成功。
我怀疑问题出在function
中的echo
语句,但我不太确定如何解决它,所以我的问题是是否有任何方法可以转换str
在 function
中不允许在 function
内进行插值?
您可以用 ""
包围变量扩展以避免 glob。
echo "$str" | ...
根据 arco444 的建议,在 function
中的 sed
之前使用 set -o noglob
就成功了。