Write a shell script which takes input of file name and prints first 10 lines of that file. file name is to be passed as command line argument. If argument is not passed then any „C‟ program from the current directory is to be selected.

SOLUTION....

#!/bin/bash
# Script to print first 10 lines of a file
# If no argument is given, select a C program from current directory

if [ $# -eq 1 ]; then
    fname=$1
else
    # Pick the first .c file in current directory
    fname=$(ls *.c 2>/dev/null | head -n 1)
fi

if [ -z "$fname" ]; then
    echo "❌ No filename given and no C program found in current directory."
    exit 1
fi

if [ -f "$fname" ]; then
    echo "✅ Showing first 10 lines of file: $fname"
    head -n 10 "$fname"
else
    echo "❌ File '$fname' does not exist."
fi

OUTPUT

Leave a Reply

Your email address will not be published. Required fields are marked *

sign up!

We’ll send you the hottest deals straight to your inbox so you’re always in on the best-kept software secrets.