kevin
kevin

Reputation: 1864

Exclude $0 when echoing the arguments of a command in a loop (BASH)?

I'm trying to use a for loop to get the filenames of files that end in .cpp.

Code:

for cppfile in ls *.cpp ; do 
echo $cppfile
done

I plan on doing more than just echoing the argument, but as it stands now, it works fine except that I'l get the command as the first arguement. Is there an easy way to avoid this, or will I have to do the loop in another fashion?

Upvotes: 1

Views: 176

Answers (3)

Dyno Fu
Dyno Fu

Reputation: 9044

find ./ -name "*.cpp" | while read cppfile; do
  echo $cppfile
  #...
done

Upvotes: 0

Alok Singhal
Alok Singhal

Reputation: 96141

As Ignacio said, you're not executing ls, your list is made up of ls and *.cpp, which gets expanded to all the files ending in .cpp. If you want to use the output of a command as a list, enclose it in backticks:

for cppfile in `ls *.cpp`
do
    echo $cppfile
done

In bash, you can use $(...) instead of backticks:

for cppfile in $(ls *.cpp)
do
    echo $cppfile
done

$(...) has an advantage that it nests better, but backticks are more portable.

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798744

You're not executing ls *.cpp there. What you're doing is iterating over "ls" followed by all the files that match "*.cpp". Removing the stray "ls" will fix this.

Upvotes: 5

Related Questions