Thursday, 5 January 2023

Unix/Linux Commands

These are some random Unix/Linux commands that we have come across and thought will be useful for tech enthusiasts,

#1 While writing a shell script if you would like to log the output of each and every command execution it is a good idea to have the script started with exec statement so that the total script output can be logged,

exec > /path/logfile.log 2>&1 

Here , File descriptor 1 is the standard output  

File descriptor 2 is the standard error

#2 typeset variable type

typeset is variable type that is used to hold a value pulled from a text file or a command output. Basically we are not pulling/assigning a value directly but it is being the result of a command or set of commands

For ex : Let's assume there is a txt file as below with three rows

check.txt 

----------------------------------

LX1 T LICENSE Test1

LX2 M LICENSE Test2

LX3 P LICENSE Test4

I would like to pull the 2nd and 4th column values from row 2 that has Test2 and then assign those values to col1 variable then here it is , 

typeset col1=`grep 'Test2' /check.txt | awk '{ print $2 , $4}'`

If the row has to be separated by field separator before printing the values then we use 'FS'

typeset col2=`grep 'Test2' /check.txt | awk 'BEGIN {FS = " "} { print $2 }'`

If at all we want a substring of a value

typeset col3=`grep 'Test2' /check.txt | awk '{ print substr($3, 3, 5) }'`

As per need the typeset variables can be echo'ed.

echo ++ col1 is ${col1}

Below is another way to use typeset variable,

typeset col4= `echo check.txt | awk 'BEGIN {FS = "/" } { print $4  }'`

#3 AWK commands

we have seen a couple awk commands in the above examples, here are some other,

date | awk ' BEGIN { print "Today date is " } OFS="/" {print $2,$3,$NF }'

who | awk '$1 == "owner" {print "Owner Name is " $1 , $2 }' 


#4 While loop

Using while loop to read lines of a file and apply various operations on them

Let's say there is a file with name check.txt

           IN_FILE=check.txt

while read LINE

do

    typeset CHECK_VAR=`echo ${LINE} | awk '{FS=","} {print            substr($1,1,4)}' `   #2016

    typeset CHECK_VAR_YEAR=`echo ${LINE} | awk '{FS=","} {print     substr($1,3,2)}' `

done < ${IN_FILE}

 

No comments:

Post a Comment

Connect Direct

One point to note below is node_id is for the Unix/Linux server file irrespective of whether it is at source or destination, for Mainframe o...