Single Line Shell Scripting

Since I started working on Terminals and writing shell scripts. Often, I have written scripts for implementing some logic that would have been contained in single line. So, following are instances on how to run loop and if-else structures in a single line of code. Also, I will be using $> to denote command prompt.

if-else-fi, if-elif-fi, while-do-done (20100710)

$> if [[ ! -z $HOME ]]; then echo $HOME; else echo "No Home"; fi

As you all might know, when you log into your terminal window. There’s an environment variable (HOME) whose value is dependent on the user who log into Terminal either through remote system, or opens Terminal after logging into any Unix-based distro.

So, its quite obvious (AFAIK), that $HOME will always have certain value. In the above code snippet, I just checked that if the $HOME has some value then display it, else show some error message.

$> if [[ ! -z $HOME ]]; then echo $HOME; elif [[ -z $HOME ]]; then echo "No Home"; fi

Taking the if-else-fi example and tweaking it a little bit as shown in this code snippet, will solve the purpose.

$> while read LINE; do echo $LINE; done < /tmp/some_file.txt

This is just  a simple while loop which will read from /tmp/some_file.txt line-by-line and displays it on console.

ls-ltr-awk, ls-ltr-grep-awk (20120906)

$> ls -ltr | awk '{print $NF}'

By default, awk uses space as delimiter and NF parameter is awk-defined parameter containing the last delimited value for the particular input. So, if one wants only the file names irrespective of characteristics mentioned in previous snippet, the current snippet would be useful.

$> ls -ltr | grep [<options>] <some-pattern> | awk '{print $NF}'

This is extremely useful when one wants to list files based on pattern which itself is not based on file name. Instead, it is based on either the user id/time stamp/month/year/file permissions. So, filtering data based on grep is useful in this scenario. Also, awk is used to get the file name, alone out-of-the-filtered detailed listing of files.

2 thoughts on “Single Line Shell Scripting

Leave a Reply

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

You are commenting using your 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