Refactoring bash scripts

Checking file permissions in terminal

$ ls -l
drwxrwxr-x 3 vagrant vagrant 4096 Jun  7 00:58 R
-rw-rw-r-- 1 vagrant vagrant    7 Jun  8 20:22 test.sh
-rw-rw-r-- 1 vagrant vagrant    7 Jun  8 20:22 test1.sh
# -rw-rw-r--
#first letter (-) indicates, it's file.
#next three letters (rw-) indicate access permissions for the user who owns the file (r - read, w - write, x - execute).
#next three letters (rw-) indicate the access permission of group memembers who owns file
# last three letter (r--) indicate the file permission for all other users.

# changing file permission
$ chmod u+x test1.sh
#indicates we want to change the permissions for the user who owns the file; + indicates that we want to add a permission; x indicates the writing permission
$ ls -l
drwxrwxr-x 3 vagrant vagrant 4096 Jun  7 00:58 R
-rw-rw-r-- 1 vagrant vagrant    7 Jun  8 20:22 test.sh
-rwxrw-r-- 1 vagrant vagrant    7 Jun  8 20:22 test1.sh

Adding shebang to scripts – It is is a special line in the script that instructs the system which executable should be used to interpret the commands.

# if we want to use bash to interpret the commands, the following line should be added,
$#!/usr/bin/env bash
# if we want to use python to interpret the commands, we should use following command,
$#!/usr/bin/env python

Changing bash scripts to more reusable way.

#!/usr/bin/env bash
curl -s http://www.gutenberg.org/cache/epub/76/pg76.txt |
tr '[:upper:]' '[:lower:]' | grep -oE '\w+' | sort |
uniq -c | sort -nr | head -n 10

# if we look at above script, the first part is input, and we can make user to change the -n 10. Therefore we can refactor the script as follows,
#!/usr/bin/env bash
NUM_WORDS="$1"
tr '[:upper:]' '[:lower:]' | grep -oE '\w+' | sort |
uniq -c | sort -nr | head -n $NUM_WORDS

#above script should run as follows,
cat data/ | ./top-words-4.sh 10 

Makingsure we can run bash script from anywhere – In order to do this, we need to add path.

#how to check the added path
$ echo $PATH | tr : '\n' | sort

#To change the PATH permanently, you’ll need to edit the .bashrc or .profile file located in your home directory. If you put all your custom command-line tools into one directory, say, ~/tools, then you’ll only need to change the PATH once.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s