sfactor
sfactor

Reputation: 13062

Creating bash script of a complex linux command

I have few long commands that I will be using on a day to day basis. So I though it would be better to have a bash script where I could pass arguments, thus saving typing. I guess this is the norm in Linux but I am kind of new to it. Could someone show me how to do it. A example is the following command

cut -f <column_number> <filename> | sort | uniq -c | 
sort -r -k1 -n | awk '{printf "%-15s %-10d\n", $2,$1}'

so i want this in a script where i can pass the filename and column number (preferably in any order) and get the desired ouput instead of having to type the whole thing everytime.

Upvotes: 2

Views: 1427

Answers (2)

Gopi
Gopi

Reputation: 10293

Create a file say myscript.sh -

#!/bin/bash
if [ $# -ne 2 ]; then 
echo Usage: myscript.sh column_number file_path
exit
fi

if ! [ -f $2 ]; then
echo File doesnt exist
exit
fi

if [ `echo $1 | grep -E ^[0-9]+$ | wc -l` -ne 1 ]; then
echo First argument must be a number
exit
fi

cut -f 10  $1 $2 | sort | uniq -c | 
sort -r -k1 -n | awk '{printf "%-15s %-10d\n", $2,$1}'

Make sure this file is executable using command chmod +x mytask.sh

You can invoke it like sh myscript.sh 30 myfile.sh or ./myscript.sh 30 myfile.sh

The first line of above script specifies the shell you would like your script to be executed in. $1 and $2 refer to the first and second command line arguments.

About argument validity checks:

  1. First check ensures that there are exactly two arguments passed to the script.
  2. Second check ensures the file pointed by the argument two is existing
  3. Third check ensures that the number passed as first argument is really a number. It uses regular expression for that purpose. May be someone provide a better replacement for this check but this is what came to my mind instantly.

Upvotes: 8

Dennis Williamson
Dennis Williamson

Reputation: 359955

To accept the filename and column number in any order, you'll need to use option switches. Bash's getopts allows you to specify and process options so you can call your script using scriptname -f filename -c 12 or scriptname -c 12 -f filename for example.

#!/bin/bash

options=":f:c:"
while getopts $options option
do
    case $option in
        f)
            filename=$OPTARG
            ;;
        c)
            col_num=$OPTARG
            ;;
        \?)
            usage_function    # not shown
            exit 1
            ;;
        *)
            echo "Invalid option"
            usage_function
            exit 1
            ;;
    esac
done
shift $((OPTIND - 1))
if [[ -z $filename || -z $col_num ]]
then
    echo "Missing option"
    usage_function
    exit 1
fi
if [[ $col_num == *[^0-9]* ]]
then
    echo "Invalid integer"
    usage_function
    exit 1
fi
# other checks
cut -f 10  $col_num "$filename" | ...

Upvotes: 1

Related Questions