Iterating over file (and directory) names with bash

后端 未结 2 772
一整个雨季
一整个雨季 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 08:00

    I think that Jonathan Leffler's answer is exactly what you need.

    An alternative that shows the power of bash arrays and eliminates the need for loops:

    shopt -s nullglob
    dirs=(*/)
    ndir="${#dirs[@]}"
    files=(*)
    nfile=$(( "${#files[@]}" - ndir))
    echo "files=$nfile, directories=$ndir"
    

    This works as follows:

    • dirs=(*/) creates an array of the names of the directories.

    • ndir="${#dirs[@]}" counts the number of directories.

    • files=(*) creates an array of the names of all files and directories.

    • nfile=$(( "${#files[@]}" - ndir)) computes the number of files by taking the number of elements of files and subtracting from that the number of directories.

    • echo "files=$nfile, directories=$ndir" prints out the results.

    This will only work in a shell, like bash, that supports arrays. On many systems, sh is dash which does not support arrays. So, use bash script when executing this script.

提交回复
热议问题