DEV Community

abbazs
abbazs

Posted on • Edited on

1

Shell script recipes

How to execute a command in all the sub directories in linux?

Consider there is a need to execute a command in all the sub directories of a directory, how to do it using bash script?

# In this example `du -ksh` is executed to get the size of each sub directory 
##Get disk usage of all sub directories#########################
function duall(){
    for d in */; do
        if [ -d "$d" ]; then
            echo "$d"
            cd "$d"
            du -ksh # Replace this line with any command required
            cd ..
        fi
    done
}
Enter fullscreen mode Exit fullscreen mode

Add the function to the .bashrc file in the home directory and below the function add an alias for the function:

alias duall="duall" # Disk usage of all sub directories
Enter fullscreen mode Exit fullscreen mode

Now the function duall available as a command.


How to remove all the files of a given type recursively?

find . -name "*.bak" -type f -delete
Enter fullscreen mode Exit fullscreen mode

Warning: If the -delete is issued before -name option, find will delete all the file.


How to tar all the folders and file except few?

tar --exclude='./folder' --exclude='./upload/folder2' -zcvf /backup/filename.tgz .
Enter fullscreen mode Exit fullscreen mode

Reference


How to retain the folder structure while archiving using 7z?

It helps to create a archive file with full path later to exactly recreate the same folder structure while extracting the zip file.

7z a -spf some.zip ./folder/subfolder/*
Enter fullscreen mode Exit fullscreen mode

While extracting the some.zip file all the folder structure will be retained.

7z x some.zip
Enter fullscreen mode Exit fullscreen mode

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Imagine monitoring actually built for developers

Billboard image

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay