Home Linux Write a script for printing all file related information in present working directory

Write a script for printing all file related information in present working directory

by Anup Maurya
24 minutes read

In this lab, we’ll create a script for printing all file related information in present working directory (e.g.: size, permission & size etc…)

Prerequisites:

  • How to execute a bash script.
  • How to change execute permission of a file.
  • How read man-page of a command.

Objective:

  • To understand how to write and execute a basic bash script

Requirements:

  • When you run the script, display all file information from current working directory

Solution:

#!/bin/bash

# Define the directory to list files in (the current directory by default)
directory="$PWD"

# Check if a directory was provided as an argument
if [ "$#" -eq 1 ]; then
    directory="$1"
fi

# Use the ls command to list file information in the specified directory
ls -la "$directory"

Output

~/fileinfo$ chmod u+rwx main.sh
~/fileinfo$ ./main.sh
total 20
drwxr-xr-x 1 runner runner 126 Oct 18 15:03  .
drwxrwxrwx 1 runner runner  68 Oct 18 15:02  ..
drwxr-xr-x 1 runner runner  12 Oct 12  2021  .cache
-rw-r--r-- 1 runner runner   0 Oct 18 15:03 'Family Info.json'
-rw-r--r-- 1 runner runner   0 Oct 18 15:02  hello.txt
-rwxr--r-- 1 runner runner 297 Oct 18 15:02  main.sh
drwxr-xr-x 1 runner runner   0 Oct 18 15:03  Programs
-rw-r--r-- 1 runner runner 281 Sep 22 16:06  .replit
-rw-r--r-- 1 runner runner 110 Apr  7  2023  replit.nix

related posts

Leave a Comment

Enable Notifications OK No thanks