Category Archives: Shell Script

How to …

Get number of lines of a text file and assign this value to a variable

num_lines=($(wc -l <file_name>))

Ex:
Fruits.txt

Annona
Coconut
Papaya
Mango
Nuts

We have 5 lines.

num_lines=($(wc -l Fruits.txt))
echo "The number of lines in Fruits.txt is $num_lines"

It will print “The number of lines in Fruits.txt is 5”

Write log of a command in terminal to file

<command> > <log_file>

Ex:

echo "Have a nice working day!" > happy.txt

Result:
happy.txt

Have a nice working day!

Some problems with array

Initialize an array

arr=(<element1> <element2> ...)
#===================================================
# example
arrNum=(1 2 3 4)

Access elements

${<NameOfArray>[index]}
#===================================================
# example
echo ${arrNum[1]}    # => 2

Print all elements

${<NameOfArray>[*]}    
# or 
${<NameOfArray>[@]}
#===================================================
# example
echo ${arrNum[*]}    # => 1 2 3 4

Get lengh

${#<NameOfArray>[*]} 
# or 
${#<NameOfArray>[@]}
#===================================================
# example
echo ${#arrNum[*]}    # => 4

——— Have fun! 🙂 ———