简体   繁体   中英

Pass variable to embeded “For Loop” in SH script

I have an SH script in FreeBSD that I am having issues passing the Variable "count" to a "For Loop".

If I add the

count=1

after the line

for d in $list; do

then it works but i need the variable set before this "for loop". The "count=2" prevents the "IF statement" from running a second time while completing the "for d in $list."

I assume this has something to do with local/global variable settings. But I tried several combinations without success.

function(){

for i in $data; do
    check=0
    count=1

    [ script lines removed (N/A) ]

    if [ "$check" == "0" ]; then

            [ script lines removed (N/A) ]

            for d in $list; do

                    if  [ "$VAR" == "ABC" ]; then
                            :
                    else

                            if [ "$count" == "1" ]; then

                                   [ script lines removed (N/A) ]
                                   [ THIS "IF" SECTION NEEDS TO RUN ONCE ONLY ! ]

                                    count=2
                            else
                                    :
                            fi
                    fi
            done
    else
            :
    fi
done

}
#!/bin/bash

list="foo bar baz"
count=1

for d in $list; do
  if [ $count -eq 1 ]; then
    echo "Tada"
    count=2
  fi
  echo $d
done 

so where's the issue now ? I have no FreeBSD to check it there, so tell me if it works for you or not.

Solution - My issue was that I used the same variable name at the top of this script.

count=$(cat $data | wc -l)
echo "Found count [ $count ]"
count=1

So, my solution was to change the variable name used by the "IF Statement"

"count" to "pcount"


count=$(cat $data | wc -l)
echo "Found count [ $count ]"
pcount=1

I don't understand why re-setting the second count=1, didn't work?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM