Some Bash tricks

Spread the love

Hi, This is an old blog post that happened to be in my drafts, so posting it here. It includes some basic Bash tricks that are helpful for newcomers.
Came across to using Bash for a simple program, and seems quiet powerful. Some things I learnt:
* $test replaces the value of the variable at that place. So

test=abc

will assign string “abc” to variable test, and

test=$abc

will assign value of variable abc to test
* You can create functions in pretty much the same way.

function myFunction() {
  # Some functionality here
}

Calling a function is different

var=$(myFunction arg1 arg2)

These args are represented in the function as $1, $2
And the return value of the function is given the above expression for var. So $var prints the output for the function.
Try this code yourself and see what it does:

function myFunction() {
        echo $1
        echo $2
}
var=$(myFunction a b)
echo $var

* You can create ‘for’ loops. One example is creating for loops from 1 to some number

for i in `seq 1 5`;
    do
        # Some functionality
    done

* Want to find a file with some regular expression? Say all files that start with abc?
Use find

    find . -name "abc*"

* Want more functionality? Want to run some command on all of these files? Let’s use piping in Bash.

	find . -name "abc*" |
		 (while read n;
			do;
                        # Do something here, filename is $n
 			done
		)

Wait, there isĀ something important here. The code inside do…done runs in a new subshell, so it becomes difficult to take output from this subshell directly. The variables set in this subshell won’t be available outside. Pretty irritating for a new comer.
And no, Even globals don’t work since it is a separate subshell šŸ™
So, how do we access some value from inside the subshell?
There are multiple ways of doing this, but this is my favourite, its clean and not complicated:
1- Create a function and take input from your main script
2- The output of this function is taken using echo and read in the main script

function myLoop()
{
    find . -name "$1*"|
    (while read n;
        do
          echo 'something'
        done
     )
}
var=$(myLoop "abcde")
echo $var

abc here is the parameter input $1 for myLoop()
Output will be ‘something’ printed the number of times you have a file which starts with abcde.
A simple trick would be to change that echo to an increment statement and in the end echo in order to return to the script as var. It will basically give a count of the number of files. And here you can add your own filters too using if and fi.
Hope you found this post informative and interesting.

You may also like...

Leave a Reply

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