Вопрос

I have some tcsh scripts that I need to port to bash scripts. I did my research on the if, input/output syntax, etc but I am stuck on porting a foreach tcsh loop into a for loop and I am looking for some help.

The tcsh code looks like this:

set num_ids = 0
foreach x(`ls item.*.txt`)
   echo $x
   set item_id = `echo $x | cut -f2,2 -d\.`
   echo $item_id
   if ( $num_ids == 0) then
      echo $num_ids
   else
      echo "not in 0"
      echo $num_ids
   endif
   @ num_ids = $num_ids + 1
   echo "printing again $num_ids"
end # end for loop 

How would you port that snippet into bash code?

Thanks!

Это было полезно?

Решение

You could do it this way:

num_ids=0

for x in item.*.txt; do
    echo "$x"
    item_id=${x#item.}; item_id=${item_id%.txt}  ## same as item_id=$(echo "$x" | cut -f2,2 -d\.) but better
    echo "$item_id"
    if [[ num_ids -eq 0 ]]; then
        echo "$num_ids"
    else
        echo "not in 0"
        echo "$num_ids"
    fi
    (( ++num_ids ))  ## same as (( num_ids = num_ids + 1 ))
    echo "printing again $num_ids"
done

Note: foreach x([bq]ls item.*.txt[bq]) should actually be for x in $(ls item.*.txt) but using ls is probably not necessary.

Your if else fi block could also be simplified as:

    echo "$item_id"
    [[ num_ids -ne 0 ]] && echo "not in 0"
    echo "$num_ids"
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top