开发者

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
开发者_Python百科

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?


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.


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜