# Why bash scripting language ? Bash shell can be present on any computer with Linux, BSD, MacOS even Windows with busybox and other tools. So it makes sense that's useful for different operations as processing text files and creating reports, html pages, automate tasks, etc. # EXAMPLE 1. Writing a hello world script. When running this script it will display Hello World: 1. open terminal 2. edit a file using any editor you prefer, example here is with vim: vim hello_world.sh 3. type inside edited file these 2 lines ( ignore ``` characters that marks code area): ``` #!/bin/bash echo "Hello World!" ``` 4. Save the file. (in vim press ESC then :wq ) 5. make the file executable: chmod +x hello_world.sh 6. run the bash script you just created by typing next line then ENTER and see the output. ./hello_world.sh Hello World! the first line is not needed if bash is default shell and accessible, and it should contain the location of bash program otherwise. Note: in any other example you can create a new file as above and paste the text inside with or without the first line #!/bin/bash as needed. # EXAMPLE 2. Printing Hello World 10 times: ``` for i in {1..10} do echo "Hello World ! ($i)" done ``` # EXAMPLE 3. Printing first 2 lines of each text file in current directory: ``` for i in *.txt do echo " => file to look into: $i" head -2 $i done ``` # EXAMPLE 4. using external lines.csv file as lines input ``` for i in $(cat lines.csv) do echo " => line to process: $i" done ``` # EXAMPLE 5. Using IF and read making an interactive program to test age groups. This is more complex as it incorporates infinite loop with while, checking if input value is a number. ``` while : do read -p "Input your age (q to exit): " AGE if ! [[ $AGE =~ ^[0-9]+$ ]] ; then echo "Exiting. Not a number" >&2; exit 1 fi if [ $AGE -lt 13 ]; then echo "You are a kid." elif [ $AGE -lt 20 ]; then echo "You are a teenager." elif [ $AGE -lt 65 ]; then echo "You are an adult." else echo "You are an elder." fi done ``` # EXAMPLE 6. Creating a menu with options using CASE command This is a very functional example, the options from the menu, used as a function, can be used interactively when running the script or as input arguments like this: ./example5.sh 1 ./example5.sh 2 ./example5.sh 3 respectively for showing current user, directory or txt file in one shell command. ``` menu(){ echo -e "\n1 - show current user" echo -e "\n2 - show current directory" echo -e "\n3 - show first line of each txt file" echo -e "\n\t x,q - exit\n" read -p "your choice =>" n } [[ "$1" == "" ]] && menu || n=$1 # show menu if no arguments while : do case $n in 1) whoami;; 2) pwd;; 3) for i in `ls *.txt`; do head -1 $i; done;; x|q) exit;; *) echo "invalid option";; esac [[ "$1" != "" ]] && break || menu # breaks if no args, show menu again otherwise done ``` (to be continued)