4 Replies - 324 Views - Last Post: 31 December 2013 - 09:32 PM Rate Topic: -----

#1 salazar  Icon User is offline

  • D.I.C Addict

Reputation: 87
  • View blog
  • Posts: 539
  • Joined: 26-June 13

Problems with for loop in batch script

Posted 26 December 2013 - 11:39 AM

I'm try to manipulate objects in a directory using batch scripting. When I run this bit, the prompt says there's a syntax error. I believe the error is occurring in the list section of the for loop construct. I thought I've seen this done previously. Can someone help me?
for %%d in (dir) do
	echo %%d


This post has been edited by salazar: 26 December 2013 - 11:41 AM

Is This A Good Question/Topic? 0
  • +

Replies To: Problems with for loop in batch script

#2 Lemur  Icon User is offline

  • Pragmatism over Dogma
  • member icon


Reputation: 1359
  • View blog
  • Posts: 3,424
  • Joined: 28-November 09

Re: Problems with for loop in batch script

Posted 28 December 2013 - 06:58 PM

I can't tell why in the world you're using %%d, it just foregrounds a job.

In C-like languages, the equivalent is a foreach loop:
foreach file in directory do
  something
end



...but in bash it's
for file in `dir` do
  echo $file
done



file is the iterated variable, dir is the collection of strings from which it is pulling. Backticks `` execute a command, or $().

In Bash you have to have end statements. This isn't Python.

This post has been edited by Lemur: 28 December 2013 - 06:58 PM

Was This Post Helpful? 2
  • +
  • -

#3 no2pencil  Icon User is offline

  • Toubabo Koomi
  • member icon

Reputation: 5191
  • View blog
  • Posts: 26,901
  • Joined: 10-May 07

Re: Problems with for loop in batch script

Posted 28 December 2013 - 08:10 PM

View PostLemur, on 28 December 2013 - 08:58 PM, said:

...but in bash it's
for file in `dir` do
  echo $file
done



What I often do is create a file list variable :

files=`ls dir`
for file in ${files} do
  echo $file
done



It's the exact same thing, & I should start doing it the shorter way you did. :P
Was This Post Helpful? 1
  • +
  • -

#4 Lemur  Icon User is offline

  • Pragmatism over Dogma
  • member icon


Reputation: 1359
  • View blog
  • Posts: 3,424
  • Joined: 28-November 09

Re: Problems with for loop in batch script

Posted 28 December 2013 - 09:00 PM

Often times it is a lot nicer to have a separate variable for the sake of clarity in some cases. Other ties it gets to be excessive. Really it's a preference thing.
Was This Post Helpful? 1
  • +
  • -

#5 salazar  Icon User is offline

  • D.I.C Addict

Reputation: 87
  • View blog
  • Posts: 539
  • Joined: 26-June 13

Re: Problems with for loop in batch script

Posted 31 December 2013 - 09:32 PM

Okay, thanks for the response. That helps explain why my code doesn't work. I wonder it there is an equivalent in windows.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1