I have been struggling with the linux bash shell and wanted to learn by doing some hands-on. So here it is…
Lets get the basics right in a minute:
1. Intro: When you execute any command on the bash shell like “ls”, its actually invoking:
- either an external executable file (placed in the disk at /bin/ls or /usr/bin/pwd or /usr/bin/cat)
- or a built-in command/function as part of bash shell itself (like cd, history)
- or its a reserved keywords (like for, case, while)
To verify this, use the “type -a <commandname> ” on the bash shell and you can read through the output.

2. Exit on failure: Every command produces an exit code. Heres the plain way to check it:

When is it important? If you are writing a shell script with multiple commands and want to halt the script if any of the command fails.
So use below command at the start of the script to exit if any command fails with a non-zero exit code
# exit when any command fails
set -e
3. File Commands: To extract a filename from a path or the last directory name, use the “basename” command.

If you want to strip out the file extension also, then do this:

If one needs the directory structure, shell has you covered with the dirname command:

When you can use the dirname in real life? In a shell script, and want to switch folders (dynamically from wherever the script is run from), use like this:
$(dirname $0)/../<newfolderpath>
4. Import: Import another script into your script:
source $(dirname $0)/<newscriptpath> # if the script is in same folder
source $(dirname $0)/../<folderpath>/<scriptpath> # if the script is in diff folder
5. Return Status: return value from each executed command can be captured by a special variable $?
6. MD5: Sending a file/directory across the network is bound to have risks, which can be prevented by a linux utility like md5sum
run the md5sum * > digest which creates a hash value for all the files and the clients can run md5sum -c digest at their end to verify all the hashes match with the digest file (OK status).
If there was any file modified during the transfer, the md5sum command will not show the OK status.