Q:

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.

A:

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:

First check ensures that there are exactly two arguments passed to the script.
Second check ensures the file pointed by the argument two is existing
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.

