Iterating over file (and directory) names with bash

后端 未结 2 803
一整个雨季
一整个雨季 2021-01-25 07:18

I was trying to write a bash script for counting the number of files and the number of directories of the local directory. This was my first try:

#!/bin/bash
fil         


        
2条回答
  •  轮回少年
    2021-01-25 07:54

    Use a wild card: for file in *; do …; done. That keeps the spaces in the names correct. Consider shopt -s nullglob too. Neither your code nor my suggestion lists names starting with a dot ..

    Also, use if [ -d "$file" ] with double quotes around the variable value to avoid spacing problems.

    Hence:

    #!/bin/bash
    
    shopt -s nullglob
    files=0
    dir=0
    for file in *
    do
        if [ -d "$file" ]
        then
            dir=$(($dir+1))
        else
            files=$(($files+1))
        fi
    done 
    echo "files=$files, directories=$dir"
    

    In Bash, there are also other ways of writing the arithmetic, such as ((files++)).

提交回复
热议问题