Scripting for Linux

A compilation of various practical tasks exercises and other script related practices for Linux, including bash scripting, scripted automated maintenance, conditions, for, while, etc.

  1. Add you scripting folder, to the path, so that you can call out your scripts from within anywhere
    1. export PATH=$PATH:/home/user/scripting-exercise
  2. Create a script to print out hello world and the current date
    1. #!/bin/bash
    2. echo “Hello world”
    3. date
  3. Make sure that the script can be executed
    1. chmod +x hello-world.sh
  4. Make sure that anyone with access to the directory can run the script
    1. chmod 755 hello-world.sh // using numerical
    2. chmod a+rx hello-world.sh && chmod u+rx hello-world.sh
  5. Append additional commands to the script, so that he will print the current directory, list the content of the current directory and ping google.com 5 times
    1. echo pwd >> hello-world.sh
    2. echo ls -al >> hello-world.sh
    3. echo ping -c 3 google.com >> hello-world.sh
  6. Create a variable at the top to identify a directory and one more for a counter
    1. DIRECTORY=“test”
    2. COUNTER=0
  7. Display the variables in the terminal
    1. echo “The directory in question is: $DIRECTORY”
    2. echo “The counter begins at : $COUNTER”
  8. Use IF condition. Check if directory, specified in the variable exists, if yes print OK, or make the dir.
    1. if [ -d $DIRECTORY ]; then
      1. echo “The directory in question is present”
    2. else
      1. echo “The directory doesn’t exist, so it will be created”
      2. mkdir $DIRECTORY
    3. fi
  9. Use while loop. Check if counter is lesser or equal to 4, print out the sample line and add 1 to it.
    1. COUNTER=0
    2. while [ $COUNTER -le 4]
      1. do
        1. echo “This is sample line # $COUNTER”
        2. COUNTER=$(( $COUNTER +1 ))
      2. DONE
  10. Use for loop.

    1. #!/bin/bash
    2. for COUNT in 1 2 3 4 5
    3. do
      1. echo “This is sample line # $COUNT”
    4. done
  11. Create a script that writes the string “scripting is good”, has no exit loop [ so that it will run until user exits], Place the script in /root, give user permissions to run the script, switch to the user and run the script, now log back into root and kill it by PID. The second part with the process handling and the multi user operation will be shown in another post.
    1. #!/bin/bash
    2. while [ 1 ] ; do
      1. echo “scripting is good” > /dev/null
    3. done