아래 코드를 실행하려고하는데 if 문에서 내 함수를 사용하려고하면 -bash: [: too many arguments
오류가 발생합니다. 왜 그런가요?
미리 감사드립니다!
notContainsElement () {
local e match="$1"
shift
for e; do [[ "$e" == "$match" ]] && return 1; done
return 0
}
list=( "pears" "apples" "bananas" "oranges" )
blacklist=( "oranges" "apples" )
docheck=1
for fruit in "${list[@]}"
do
if [ notContainsElement "$fruit" "${blacklist[@]}" -a $docheck = 1 ]
then
echo $fruit
fi
done
사용할 때 if [ ... ]
실제로 [
유틸리티를 사용하고 있습니다 (과 동일 test
하지만 마지막 인수가 여야 함 ]
).
[
함수 실행을 이해하지 못하고 문자열을 예상합니다. 다행히도 [
여기서는 전혀 사용할 필요가 없습니다 (적어도 함수에 대해서는).
if [ "$docheck" -eq 1 ] && notContainsElement "$fruit" "${blacklist[@]}"; then
...
fi
정수를 먼저 확인하고 있으므로 $docheck
1이 아닌 경우 함수 호출을 전혀 피할 수 있습니다 .
This works because if
takes an arbitrary command and decides what to do from the exit status of that command. Here we use a [ ... ]
test together with a call to your function, with &&
in-between, creating a compound command. The compound command's exit status would be true if both the [ ... ]
test and the function returned zero as their exit statuses, signalling success.
As a style note, I would not have the function test whether the array does not contain the element but whether if does contain the element, and then
if [ "$docheck" -eq 1 ] && ! contains "$fruit" "${blacklist[@]}"; then ...
Having a function test a negative will mess up logic in cases where you do want to test whether the array contains the element (if ! notContainsElement ...
).
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다