Skip to main content

Posts

Showing posts with the label Bash script

Basic Ansible understanding when statement

Ansible playbook to illustrate how "when" conditional statement works in Ansible. Ansible playbook below will run a command: "file -s /dev/sdb"  The output of the command will be saved to the variable: save_the_command_output  Yes, the name of the variable can be anything. Just changed it to something that is sensible. save_the_command_output is just a string to illustrate its functionality or usage. After registering or saving the output to a variable, another command will be executed provided the conditional statement "when" is True or the condition is meet or satified. If the conditional statement is not meet then the command will be bypass or will not be executed. On this illustration below, if the conditional statement has been meet. Then a file with a filename "condition_ok" will be written on /tmp directory. Otherwise, if the condition is not meet then no file will be created. Sample playbook below: #=================== --- -  hosts: local...

Ansible comment all existing lines and add new lines

Backing up every configuration before any change is a good idea.  With the Git tool, every revision or change can be keep track and changes can be reversed. However, not everything is in Git. For example, in Linux configuration on /etc configuration or other important location or files is not under Git. To keep track of the changes, old school method can still be applied. Making another copy of the file, or just simply commenting every line and adding changes or new configuration after commenting the existing lines or configuration; are forms of backup. Existing configuration can still be seen, and can put back if there's a need to reverse the configuration. In an environment where there is hundred or more virtualized machines, Ansible is a way to go.  Ansible can do the task to comment all the existing lines and apply new configurations. Ansible script below, are references from multiple sources found on the web to create this Ansible script below. Here's the Ansible, save it...

Check multiple IPs via bash one-liner loop using ping or dig

Ping multiple Linux servers via Bash script. Pinging a Linux server sounds a very common and simple task for any SysAdmin. However, if there are quite a few IP Addresses to check, it's quite daunting as typing on the terminal window is quite tedious and prone to error or mistype. Bash script is a way to go for this type of task. Just prepare all the IP Addresses that needs to be checked in a single text file. Do a loop to check all the IP Addresses on the text file and just watch the Bash do its job. Here's a simple code to do it: for ipx in $(cat ipx.txt); do ping -c 3 $ipx; done ipx.txt <<< should contain all IP Addresses to be checked Example of ipx.txt contents: 1.2.3.4 4.5.6.7 10.10.10.1 .... .... etc.. Above command can also be used to check DNS Reverse record using dig. Example: for ipx in $(cat ipx.txt); do dig -x $ipx; done The above will perform a reverse DNS lookup. There's a lot of uses cases that can be done, with the above command. That's it. Enjo...

Zip log files via script or cron job

Zipping log files to save disk space is quite a common task for system admin. Logs can be kept for a certain period of time depending on the company policy. To keep logs files and not delete them is quite a good strategy. If something goes wrong, you will be able to trace and go back in time, and check what went wrong. Zipping log files can be done manually, or via Bash or Shell script. If the folder has a standard pattern, which is quite ideal then creating a shell script to automate the zipping of log files will be easier. For example, if  the log files is on this path /mnt/log folder. And it has this pattern, YYYY-MM-DD. Creating a script to avoid manual task can be done easily. Depending on how busy the application is, log files can grow easily and may fill-up the disk quickly. If the log folder structure is based on Year, Month and Date. Then the shell script knows what pattern to look for and the task can be automated. Example Screenshot of the log folder structure: Below is ...

How to use regex in Linux Bash

Regex or regular expression uses a pattern that is compared to a string and will check if the pattern exists or the string matches the pattern. In Bash script a simple if then else and a regex pattern can be used to check if the pattern matches a set of input on a text file. Bash script below is a simple example on how to use regex in Bash using if then else. Script below uses this sample file "number_file.txt" with the sample text or contents shown below. a12567 b23567 c34568 12w678 23908 35107 23469 x1234 y3432 12094x 123y8 ==== #!/bin/sh patx="^[0-9]+$" while IFS= read -r line; do     echo "Text read from file: $line"     if [[ $line =~ $patx   ]]                then                  echo "Hey this one is alpahumeric --> $line."      else ...

Python create multiple choices for if statement

How to compare multiple choices in Python if statement? In an if else statement, if case sensitivity is a concern on the response or input from the user. Then the expected response should be defined on the if statement. Of course, there’s a good workaround on this kind of scenario like converting all input to lowercase or uppercase then start comparing or matching. Basically, the code below is for illustration purposes only. Converting the input to lowercase or uppercase is a good option, if the program is expecting a string input. However, code illustrated below will not be useful if the input is a number. In which case, converting the input to lowercase or uppercase will not help. Anyway, code below uses the string T, True or true as possible input that will display this message” You must have seen the sun! Or hoping to see the sun at the end of the tunnel!” if it matches “T, True or true”. If the input is TRUE, or other letter other than the characters mentioned above it...

PowerShell read text file at a specific or certain lines

Reading log files or text file is quite basic and log files should be reviewed or else recording the logs if of no point. PowerShell code below read the 2 nd line of a specific text file specified on the path.   $logs = get-content c:\dev\log1.txt   "Line number 2 in log1.txt is: {0}" -f ( $logs [ 2 ] )     PowerShell code below uses a loop to read number of lines on a specific text file. $logs = get-content c:\dev\log1.txt   ForEach ( $line_number in 0 .. 10 ) {   "Line number $line_number is : {0}" -f ( $logs [ $line_number ] )}     Using above code, 0 is equal to line 1.   So, to read the first line code should be like this:     $logs = get-content c:\dev\log1.txt   "Line number 1 in log1.txt is: {0}" -f ( $logs [ 0 ] )     To read the last line: $logs = get-content c:\dev\xtest.txt -Tail 1 $logs     If above command will return an emp...

Bash save Linux command output to a variable

How to save the output of a command to a variable in Bash script? In Bash getting the output of a command line in terminal is sometimes necessary when doing Bash/Shell script. For example, if need to monitor a specific service whether it is installed, running or disabled. Getting the output of the command that checks the status of specific service is quite important, so the script will know on what to execute. If the specific output shows that the service has stopped then the script can decide to start the service, or if the output shows that a specific service or software is not installed then an option to install the software can be done. Here’s an example on how to save the status of a specific output to a variable using Bash. #!/bin/bash dcommand=$(systemctl status gdm.service) command_output=$(echo "$dcommand") str_running='Active: active (running)' if [[ "$command_output" == *"$str_running"* ]]; then   echo "It's the...

Bash slice string in Linux Shell

Strings are quite basic in any scripting or programming languages. If a journey to a thousand miles starts with a single step, in the programming world the journey starts with a string called “Hello World” and beyond “Hello World” pseudocode and algorithm will keep the journey going.   Strings in scripting or programming are just group of characters. So, if string is a group of characters then it can be slice by character or a sub-string can be taken from the string. To slice a string in Bash, a syntax which is part of the Bash library can be used. Syntax is: ${string_to_be_sliced:slice_start_position:slice_end_position} Example string: slicethestring=“Hello Algorithm World” The string is stored in a variable: slicethestring To get the sub-string “Algorithm World”. Code will be:   echo ${slicethestring:6:23} #start the slice at position 6 till position 23 Another way to slice the string from a specified start position till the end; is to tell Bash the star...

PowerShell switch case call function

Code below collect user input and uses switch case statement to check if the input matches, and if it matches a function is called that will execute commands. Here’s the code: #get or read from user input $computer_name = read-host ( "Enter Computer Name:" )   switch ( $computer_name )   {     #if the input is computer_1 then function func_comuputer1 is called   computer_1     { func_computer1 }     computer_2     { func_computer2 }   }     #function called if computer_1 is the input function func_computer1 {   write-host "You entered Computer_1" #or replaced with other function like reboot / shutdown /or other commands #Restart-Computer -ComputerName computer_1   }   #function called if computer_2 is the input function func_computer2 {   write-host "You entered Computer_2" #or replaced with other function like reboot / shutdown /or other c...