Friday, July 25, 2008

[Bash] Include a shell script within another one

I just found out today how to include a shell script into another one.
It doesnt use the keyword 'include' like in javascript or php.
A simple dot '.' will just do the trick.

===== bash1.sh =======
#!/bin/bash

export MESSAGE="Hello World"
export MESSAGE2="Hello World 2"
echo $MESSAGE
echo $MESSAGE2

===== bash2.sh =======

#!/bin/bash

. bash1.sh
echo $MESSAGE
echo $MESSAGE2

When running bash2.sh, you will see:

Hello World
Hello World 2
Hello World
Hello World 2

Explanation:
You may think that running the bash1.sh script with :
./bash1.sh
would work but no. Why?
When running ./bash1.sh (or a call to the bash1.sh script with an absolute path), the current shell will create a child process and run the bash1.sh script within it.
When the child process finished, bash2.sh carries on but doesnt display anything for the

echo $MESSAGE
echo $MESSAGE2

lines
For this you will have to run the bash1.sh script within the current shell instead of creating a child process. And you are doing this by using the '.' or you can use the 'source' command.

'.' or 'source' will run the bash1.sh in the current shell, so when bash1.sh will finish to run , the environment variables $MESSAGE and $MESSAGE2 set from bash1.sh will persist wihtin the current shell and you' ll be able to use them from bash2.sh

Friday, July 4, 2008

[Bash] Populate command line with occurrences

Little tip for bash users:

Let's say you want to delete all files in a directory that starts by 'exam' except one. I would use 'rm' and put all the file names I want to delete manually as there is just one I want to keep.
By typing:

rm exam[ESC + *]

the command [ESC + *] will populate the argument line with all occurrences of 'exam'.

And now, you can remove the file you want to keep from the list.

If you're lucky and the file you want to keep is the last one, a simple [Ctrl + W] will remove the last argument passed in the command line.

The tip was found here(in french)