User Tools

Site Tools


cs:bash_language:example_1
Return to Home page

Example 1

Concepts:
Extraction of some statistics regarding files (if and for statements)

Text:
Implement a bash script with the following interface:

  • summary.sh dir

The script must scan the content of the dir directory and it must print a summary of the its content in a file named summary.out.

Particularly, for each element of dir:

  • if the element is a file: the name of the file and the first 10 characters (bytes) must be printed in the ./summary.out file
  • if the element is a directory: the name of the directory and the number of files or subdirectory it contains must be printed in the summary.out file.

An example of the summary.out file should be:

ex: 23 elementi
lez5.txt: content of
example.sh: #!/bin/bas

Solution:

summary.sh
#!/bin/bash
 
if [ $# -ne 1 ] ; then
    echo "Usage $0 <dir>"
    exit 1
fi
 
if [ ! -d "$1" ]
then
    echo "$1 is not a directory"
    exit 1
fi
 
cd "$1"
rm -f summary.out
for i in * ; do  # for i in $(ls) ; do
    if [ -d "$i" ] ; then
        echo "$i": $[`ls -l "$i" | wc -l`-1] elements >> summary.out 
    elif [ -f "$i" ] ; then
        echo "$i": $(head -c 10 "$i") >> summary.out
    fi
done
 
exit 0

If you found any error, or if you want to partecipate to the editing of this wiki, please contact: admin [at] skenz.it

You can reuse, distribute or modify the content of this page, but you must cite in any document (or webpage) this url: https://www.skenz.it/cs/bash_language/example_1
/web/htdocs/www.skenz.it/home/data/pages/cs/bash_language/example_1.txt · Last modified: 2024/04/08 22:35 by 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki
Privacy Policy