在循环 - shell脚本中获取函数的返回值

时间:2017-03-07 07:46:14

标签: function shell return

似乎无法理解以下代码段的输出。尝试在循环中打印函数返回值

contains () {
 local e
 for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done
 return 1
}


line="ayush"
line2="this is a line containing ayush"
contains $line $line2
echo $?  #prints 0
for i in 1 2 3;do
    contains "$line" "$line2"
    echo $? #prints 1 everytime
done

1 个答案:

答案 0 :(得分:1)

@Ayush Goel

问题在这里,

contains () {
  local e
  for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done
  return 1
}


line="ayush"
line2="this is a line containing ayush"

contains $line $line2
echo $?  #prints 0

for i in 1 2 3;do
   contains $line $line2   # <------------------ ignore ""
   echo $? # Now it will print 0 
done

$ var和&#34; $ var&#34;之间的差异:

1)$ var case

var="this is the line"
for i in $var; do
    printf $i
done

这里会打印

this is the line

表示使用空格扩展$ var

<强> 2)&#34; $变种&#34;情况下

var="this is the line"
for i in "$var"; do
    printf $i
done

这将打印

this

这里&#34; $ var&#34;将被视为单个参数,它将只从列表中获取一个值。