解决上述问题的另一种方法是将每个字符串设置为一个变量,然后使用以文字美元符号表示的变量来调用该函数\$
。然后在函数中使用eval
读取变量并按预期输出。
#!/usr/bin/ksh
myFunction()
{
eval string1="$1"
eval string2="$2"
eval string3="$3"
echo "string1 = ${string1}"
echo "string2 = ${string2}"
echo "string3 = ${string3}"
}
var1="firstString"
var2="second string with spaces"
var3="thirdString"
myFunction "\${var1}" "\${var2}" "\${var3}"
exit 0
输出为:
string1 = firstString
string2 = second string with spaces
string3 = thirdString
在尝试解决与此类似的问题时,我遇到了UNIX问题,认为我的变量是空间限定的。我试图将管道定界字符串传递给函数,该函数awk
用于设置一系列变量,这些变量随后用于创建报告。最初,我尝试了ghostdog74发布的解决方案,但由于并非所有参数都都用引号引起来,因此无法使其正常工作。将双引号添加到每个参数后,它便开始按预期运行。
以下是我的代码的before状态,after状态可以正常运行。
之前-无效代码
#!/usr/bin/ksh
#*******************************************************************************
# Setup Function To Extract Each Field For The Error Report
#*******************************************************************************
getField(){
detailedString="$1"
fieldNumber=$2
# Retrieves Column ${fieldNumber} From The Pipe Delimited ${detailedString}
# And Strips Leading And Trailing Spaces
echo ${detailedString} | awk -F '|' -v VAR=${fieldNumber} '{ print $VAR }' | sed 's/^[ \t]*//;s/[ \t]*$//'
}
while read LINE
do
var1="$LINE"
# Below Does Not Work Since There Are Not Quotes Around The 3
iputId=$(getField "${var1}" 3)
done<${someFile}
exit 0
售后服务代码
#!/usr/bin/ksh
#*******************************************************************************
# Setup Function To Extract Each Field For The Report
#*******************************************************************************
getField(){
detailedString="$1"
fieldNumber=$2
# Retrieves Column ${fieldNumber} From The Pipe Delimited ${detailedString}
# And Strips Leading And Trailing Spaces
echo ${detailedString} | awk -F '|' -v VAR=${fieldNumber} '{ print $VAR }' | sed 's/^[ \t]*//;s/[ \t]*$//'
}
while read LINE
do
var1="$LINE"
# Below Now Works As There Are Quotes Around The 3
iputId=$(getField "${var1}" "3")
done<${someFile}
exit 0