Bash How to Trim String

Bash How to Trim String

You can use a bash parameter expansion, sed, cut and tr to trim a string.

Let’s use bash parameter expansion to remove all whitespace characters from the variable foo:

foo="Hello world."
echo "${foo//[["space:]]/}"

Output: Helloworld.

“${foo// /}” removes all space characters, “$foo/ /” removes the first space character.

To remove only space characters before and after string use sed:

foo=" Hello world. "
echo "${foo}" | sed -e 's/^[[:space:]]*//'

Output: Hello world.

Easy to use and remember the way how to remove whitespaces before and afterword:

echo " text. text2 " | xargs

xargs remove all whitespaces before “text.” and let one space between text. and text2.

If you want to delete only the last character from the variable:

foo="hello"
echo "${foo::-1}"

Output: hell

Bash How to Sum Variables

Bash How to Sum Variables

Let’s define two variables:

FILES_ETC=1416
FILES_VAR=7928

If you want to get total value, you can do:

TOTAL_FILES=$((FILES_ETC+FILES_VAR))
echo $TOTAL_FILES

For 100% compatibility with old shells, you can use external command expr. In modern systems (ec. Centos 7 64bit), in fact, expr is not an external command. It is an internal shell function. So there is not a significant difference in speed between the above and this command:

TOTAL_FILES=`expr $FILES_ETC + $FILES_VAR`
echo $TOTAL_FILES

Funny thing is that there must be spaces between arguments. In fact, expr is a command, $FILES_ETC is the first argument, + is the second argument and $FILE_VAR is the third argument.

If you want to add numbers with decimal points, you can use bc. bc is a very useful external command for making arithmetical operations:

TOTAL_FILES=$(echo $FILES_ETC + $FILES_VAR | bc)
echo $TOTAL_FILES

Common mistakes are spaces before or after ‘=’ sign. However bc and expr commands expect spaces between arguments and operators, so in these cases don’t forget to spaces.

Difference between a Kernel and Shell

Difference between a Kernel and Shell

A shell is a command interpreted, way to communicate with the operating system and kernel using the command line.

Consider what would happen if we have only kernel and no shell ?. We would have a device with OS but there is no method to use it. We need to have an interface between OS and humans. That’s shell’s purpose

A kernel is a low-level program interfacing with the hardware in privileged mode. It is an essential part of the system. Any requests from the shell is processed by the kernel.

It is impossible to have a shell without a kernel. Without a kernel, we can not execute commands.

A kernel is the lowest level program running on computers. The kernel does task scheduling, handles filesystems, I/O handling, memory management.

Best Shell IDE

Best Shell IDE

There is no shell scripting ide. There are some examples of text editors that help you to write code.

1. Sublime Text

Sublime Text has many powerful features that make coding painless. It has all basic features mentioned on this page and many others like multi-select (hold CTRL and put mouse cursor in another line), creating your own snippets(lines of code that repeat), minimap(zoomed view of entire file).

2. Atom

Atom is developed by Github so it supports Github integration. It is often called the “hackable IDE of 21st century”, so you could easy customize almost everything.

Cool visual extension is “Power mode”, every time you hit a key, editor does a little move, like you hit the screen.

3. Geany

Geany is a lightweight IDE, aims to provide fast development environment. Features: filebrowser, save actions( autosave, instantsave, backupcopy), split window. In ubuntu you can install Geany using apt:

sudo apt-get install geany

4. Kate

It is a pre-installed text editor in Kubuntu. Some of the useful features: embedded terminal, SQL plugin, find and replace, syntax highlighting, bracket matching, auto backup, auto-completion with argument handling.

Bash How to Rename Directory

Bash How to Rename Directory

Use the “rename” command. Syntax of rename command:

rename [options] expression replacement file

If we want to rename directory “old-name-dir” to “new-name-dir”:

rename 'old-name-dir' new-name-dir old-name-dir

To preview change type the “ls” command.

You can rename the directory with the “mv” command:

mv old-name-dir/ new-name-dir

It will rename old-name-dir to new-name-dir. If old-name-dir contains any files, it is good advice to add option -R after mv.

Bash How to Escape Single Quote

Bash How to Escape Single Quote

Enclosing characters or variables in single quotes (‘) represents the literal value of characters. Example:

$foo="Hello world"
echo '$foo'

Output: $foo

If you want to write the content of variable $foo in ‘ use the character \ to escape a single quote.

echo \'$foo\'

Output: ‘Hello world’

In single quotes, escaping a single quote is not possible, thus you can’t include a single quote into single quotes

Instead of single quotes use double quotes (“):

echo "Hello'world"

Output: Hello’world

Single quote may not occur between single quotes, even when preceded by a backslash, but this works:

echo $'I\'m a linux admin.'

Output: I’m a linux admin.

Linux Commands Cheat Sheet

Do you want to learn the Linux commands? If yes, then you are in the right place. There are uncountable commands in Linux. Generally, we use some of the Linux commands from the Linux commands cheat sheet regularly to perform the common tasks.

pythonarray.com is a free Python tutorial website for people who want to learn Python, fast.

You can also learn Google Sheets Tips – New Google Spreadsheet Hacks, Tricks with Examples

Types of Linux Commands

All the Linux commands are categorized into 7 different types. They are Basic Linux commands, File permission commands, Environment variables commands, User management commands, Networking commands, Process commands, VI Editing commands, Other Commands.

We are giving a detailed explanation for each and every Linux command with their examples for easy learning in the below sections. Have a look at them and follow them. Check the actual description of each Linux command in their manual page.

Basic Linux Commands

  • ls command:

It is used to list all files and directories of a directory. The ‘-l’ option gives the long listing format. Its syntax is $ ls [options] [file|dir]

Example: $ ls -l samplefile

  • ls-R command:

It gives the lists files in subdirectories. List recursively directory tree and syntax is $ ls -R [options] [file|dir]

Example: $ ls -R samplefile

  • ls -a Command:

It lists all files including hidden files starting with’.’ Its syntax is $ ls -a [options] [file|dir]

  • ls -al Command:

It lists all files details and directories with detailed information like permissions, size, owner, etc. Syntax is $ ls -al [options] [file|dir]

  • cd or cd ~ Command:

This command will navigate to the home directory or change the directory. Its syntax is $ cd [directory]

Example: $ cd Directory1

  • cd .. Command:

It moves one level up. Syntax is $ cd . . [directory]

  • cd Command:

Use this command to change to a particular directory. Its syntax is $ cd [directory]

Example: $ cd directory1

  • cd / Command:

This command will move to the root directory. Syntax is $ cd /

  • cat filename Command:

Create a new file using this command in Linux. Its syntax is $ cat filename.

Example: $ cat filename1

  • cat filename Command:

It displays the content in that particular file. The syntax is $ cat filename.

Example: $ cat filename1.

  • cat file1 file2 file3 Command:

It combines two files namely file1 and file2 and stores the output in a new file called file3. Its syntax is $ cat file1 file2 file3.

Example: $ cat add multiply arithmetic.

  • mv file “new file path” Command:

It moves the files to the new location. Syntax is $ mv file “new file path”.

Example: $ mv add “E:/Arithmeticopeartions/”.

  • mv filename new_file_name Command:

It renames or changes the file name to a new file name. Syntax is $ mv filename new_file_name.

Example: $ mv add sum

  • sudo Command:

sudo command allows a permitted user to run a command as root or another user. It runs commands in superuser mode. The syntax is $ sudo filename option

Example: $ sudo apt update

  • rm Command:

It is used to remove the files or directories. Syntax is $ rm filename or $ rm directory

Examples: $ rm sum and $ rm mydrive

  • man Command:

It is used to view the online reference manual pages for the commands or programs. It provides the help information of any commands. Its syntax is $ man commandname

Example: $ man cd

  • history Command:

It produces the list of previously used commands and gets the all past commands types in the current terminal session. The syntax is $ history

  • clear Command:

clear command is helpful to clear the terminal screen. The syntax is $ clear

  • mkdir directoryname Command:

It creates a new directory in the present working directory or at any specific path. Syntax is $ mkdir directoryname

Example: $ mkdir new_directory

$ mkdir -p new_directory: Here -p option is used to override the already available directory.

  • rmdir Command:

It helps to remove/ delete the empty directories. Syntax is $ rmdir [directory_name]

Example: $ rmdir new_directory

  • mv Command:

It is helpful to rename files or directories. mv command also moves a file or a directory to another location in the directory structure. Its syntax is $ mv file1 file2

Example: $ mv add sum

  • pr -x Command:

It divides the file into x columns. Syntax is $ pr -x filename.

Example: $ pr -5 add

  • pr -h Command:

It is useful to assign a header to the file. Syntax is $ pr -h filename

Example: $ pr -h sum

  • pr -n Command:

This command denotes the file with the line numbers. Its syntax is $ pr -n file

Example: $ pr -n sum

  • lp -nc , lpr c Command:

It prints the c number of copies of a file. lp stands for a line printer. Its syntax is $ lpr c filename

Example: $ lpr 5 sum

  • lp -d lp -P Command:

It specifies the name of the printer. The syntax is $ lp -P

  • apt-get Command:

It is a powerful and free front end package manager for Debian/Ubuntu systems. It is used to install new software packages, remove available software packages, upgrade existing software packages, and upgrade the entire operating system. Its syntax is $ apt-get package

Example: $ sudo apt-get update

  • mail -s ‘subject’ -c ‘cc-address’ -b ‘bcc-address’ ‘to-address’ Command:

It is a linux command used to send mail. Syntax is $ mail -s ‘subject’ -c ‘cc-address’ -b ‘bcc-address’ ‘to-address’

Example: $ mail -s ‘regarding_job’ -c ‘add@gmail.com’ -b ‘sum@gmail.com’ ‘arithmetic@gmail.com’

  • mail -s “Subject” to-address < Filename Command:

It is used to send an email with an attachment. Its syntax is $ mail -s “Subject” to-address < Filename

Example: $ mail -s “Addition of Numbers” sum@gmail.com < Addition

File Permission Commands

  • ls-l Command:

Use this command to show file type and access permission of any particular file. Syntax is $ ls-l filename

Example: $ ls-l sum

  • r Command:

It is used to give read permission to a file. The syntax is $ r filename.

Example: $ r sum

  • w Command:

It gives write permission to the file. The syntax is $ w filename

Example: $ w sum

  • x Command:

It is useful to provide execute permission to the file. Its syntax is $ x filename

Example: $ x sum

  • -= Command:

This command is used when you want to give no permission to a file. Syntax is $ -= filename

Example: $ -= file1

  • Chown user Command:

It is helpful to change the ownership of a file/directory. The syntax is $ chown user filename

Example: $ chown user file1

  • Chown user:group filename Command:

It changes the user and group for a file or directory. Syntax is $ chown user:group filename

Example: $ chown user:group sum

Environment Variables Command

  • echo $VARIABLE Command:

It displays the value of a variable or prints a text of the line. Its syntax is echo [option] [string]

Example: $ echo “Print this line” or $ echo $VARIABLE var1

  • env Command:

It lists all environment variables. The syntax is $ env

  • VARIABLE_NAME= variable_value Command:

It creates a new variable and assigns it a value. Syntax is $ VARIABLE_NAME= variable_value

Example: $ My_Variable= 10

  • Unset Command:

It removes a variable. Syntax is $ Unset VARIABLE_NAME

Example: $ Unset My_Variable

  • export Variable=value Command:

It is helpful to set the value of an environment variable. Syntax is $ export Variable=value

Example: $ export Variable1=90

User Management Commands of Linux

  • sudo adduser username Command:

It is used to create a username. The syntax is $ sudo adduser username

Example: $ sudo dduser user1

  • sudo passwd -l ‘username’ Command:

It is helpful to change the user password. Syntax is $ sudo passwd -l ‘username’

Example: $ sudo passwd -l ‘user1’

  • sudo userdel -r ‘username’ Command:

This command is used to add and delete users on Linux. Syntax is $ sudo userdel -r ‘username’

Example: $ sudo userdel -r ‘user1’

  • finger Command:

It is a user information lookup command which provides details of all users logged in. The Syntax $ finger

  • finger username Command:

It gives the login details of that particular user. Syntax $ finger username

Example: $ finger user1

Networking Commands

  • SSH username@ip-address or hostname Command:

You can log in to a remote Linux machine using SSH. The syntax is $ SSH username@ip-address or hostname

Example: $ SSH user1@https:11//1001

  • Ping hostname=”” or =”” Command:

It is used for analyzing the network and host connections. Syntax is $ Ping hostname=”” or =””

Example: $ Ping hostname=”host1″

  • dir Command:

It displays all files in the current directory of a remote computer. The syntax is $ dir

  • cd “dirname” Command:

It changes the current directory to “dirname” on a remote computer. Syntax is $ cd “dirname”

Example: $ cd “E”

  • put file Command:

It is helpful to upload the file from local to the remote computer. The syntax is $ put file

Example: $ put sum

  • get file Command:

It is used to download the file from remote to the local computer. The syntax is $ get file

Example: $ get add

  • quit Command:

It is used to logout from that network. The syntax is $ quit

Process Commands

  • bg Command:

You can send a process to the background with this command. The syntax is $ bg processname

Example: $ bg process1

  • fg Command:

To run a stopped process in the foreground. The syntax is $ fg processname.

Example: $ fg process1

  • top Command:

It gives the details of all active processes in the directory. The syntax is $ top

  • ps Command:

It produces the status of processes running for a user. The syntax is $ ps username

Example: $ ps user1

  • ps PID Command:

This command gives the status of a particular process. The syntax is $ ps PID processname

Example: $ ps PID process1

  • pidof Command:

It gives the process id of a process. The syntax is $ pidof processname.

Example: $ pidof process1

  • kill PID Command:

It kills a process. The syntax is $ kill PID processname

Example: $ kill PID process1

  • nice Command:

It is used to start a process with the given priority. The syntax is $ nice processname.

Example: $ nice process

  • renice Command:

It is used to change the priority of an already running process. The syntax is $ renice processname

Example: $ renice process2

  • df Command:

It provides free hard disk space on your system. The syntax is $ df

  • free Command:

It gives free RAM space on your system. The syntax is $ free

VI Editing Commands

  • i Command:

It inserts at the cursor i.e goes to insert mode. The syntax is $ i

  • a Command:

It is used to write after the cursor in insert mode. The syntax is $ a

  • A Command:

This command is used to write at the end of the line in insert mode. The syntax is $ A

  • ESC Command:

It is helpful to terminate insert mode. The syntax is $ ESC.

  • u Command:

It undoes the last change. The syntax is $ u.

  • U Command:

It undoes all changes to the entire line. The syntax is $ U

  • o Command:

It opens a new line in insert mode. The syntax is $ o

  • dd Command:

It deletes that particular line. The syntax is $ dd line number

Example: $ dd 25

  • 3dd Command:

This command deletes 3 lines. The syntax is $ 3dd line number

Example: $ 3dd 25

  • D Command:

It deletes the contents of a line after the cursor. The syntax is $ D

  • C Command:

It is used to delete the contents of a line after the cursor and insert new text. Press the ESC key to end the insertion. Syntax is $ C

  • dw Command:

Delete a word using this command. The syntax is $ dw

  • 4dw Command:

It is used to delete 4 words. The syntax is $ 4dw

  • cw Command:

It is used to change a word. Syntax is $ cw

  • x Command:

It deletes the character at the cursor. Syntax is $ x

  • r Command:

Replace the character. The syntax is $ r

  • R Command:

It overwrites characters from cursor onward. The syntax is $ R

  • s Command:

Substitute one character under the cursor and continue to insert. The syntax is $ s

  • S Command:

Substitutes the entire line and starts to insert at the beginning of the line. The syntax is $ S

  • ~ Command:

It is used to change the case of the individual character. Syntax is $ ~

Other Linux Commands

  • adduser/addgroup Command:

adduser adds a user and addgroup adds groups to the system. The syntax is $ adduser username

Example: $ sudo adduser tech

  • agetty Command:

agetty is a program that manages physical or virtual terminals and is invoked by init. It is the substitute for Linux getty.

Example: $ agetty -L 9600 ttyS1 vt100

  • alias Command:

It is a useful shell built-in command for creating shortcuts to a Linux command on a system.

Example: $ alias home’cd /home/drive/file1′

  • apropos Command:

This is used to search and display a short man page description of a program/ command. The syntax is $ apropos commandname

Example: $ apropos rm

  • aptitude Command:

It is a powerful text-based interface to the Debian Linux/GNU package management system. The syntax is $ aptitude package

Example: $ sudo aptitude update

  • arch Command:

This command is used to display the machine architecture or hardware name. The syntax is $ arch

  • arp Command:

ARP stands for Address Resolution Protocol that maps IP network addresses of a network neighbor with the hardware (MAC) addresses in an IPv4 network.

Example: $ sudo arp-scan –interface=enp2s0 –localnet

  • at Command:

It is used to schedule tasks to run in the forthcoming time. Syntax is $ at

Example: $ sudo echo “shutdown -h now” | at -m 15:20

  • atq Command:

This command is used to view jobs in at command queue. Syntax is $ atq

  • atrm Command:

It is helpful to delete/remove jobs from the queue. $ atrm 2

  • awk Command:

Awk is a programming language created for text processing and used as a data extraction and reporting tool.

Example: $ awk ‘//{print}’/etc/hosts

  • batch Command:

It is similar to at command which is useful to schedule tasks to run in a future time. Syntax is $ batch

  • basename Command:

It helps to print the name of a file stripping of directories in absolute path. Syntax is $ basename filename

Example: $ basename samplefile

  • bzip2 Command:

It is useful to compress or decompress the files. Syntax is $ bzip2 filename

Example: $ bzip2 -z filename #Compress

$ bzip2 -d filename.bz2 #Decompress

  • cal Command:

This command is used to print a calendar on the standard output. Syntax is $ cal

  • chgrp Command:

It is used to change the group ownership of a file. Syntax is $ chgrp new_group_name filename

Example: $ chgrp Product Multiplication.txt

  • chmod Command:

It is used to change/ update file access permissions. Syntax is $ chmod permission filename

Example: $ chmod +x product.txt

  • cksum Command:

This command is used to provide the checksum and byte count of the given input file. Syntax is $ cksum filename

Example: $ cksum product.txt

  • cmp Command:

It compares byte by byte comparison of two files. Syntax is $ cmp file1 file2

Example: $ cmp sum add

  • comm Command:

It is used to compare two sorted files line by line. Syntax is $ comm file1 file2

Example: $ comm product multiplication

  • cp Command:

It copies files and directories from one location to another. Syntax is $ cp location1 location2

Example: $ cp /home/arithmetic/add /home/arithmetic/product/

  • date Command:

It displays/ sets the system date and time. Syntax is $ date

Example: $ date –set=”20 Oct 2020 10:35:05″

  • diff Command:

The double advantage of this command is used to compare two files line by line and used to find the difference between two directories. Syntax is $ diff file1 file2

Example: $ diff sum add

  • dmidecode Command:

It retrieves the hardware information of any linux system. Syntax is $ dmidecode

Example: $ sudo dmidecode –type system

  • du Command:

It shows the disk space usage of files present in the directory as well as its subdirectories. The syntax is $ du directory

Example: $ du /home/arithmetic

  • eject Command:

eject command is used to eject removable media such as CD/DVD/ROM/floppy disk from the system. The syntax is $ eject disklocation

Example: $ eject /dev/cdrom

  • exit Command:

It is used to exit a shell. The syntax is $ exit

  • expr Command:

It is used to calculate an expression. The syntax is $ expr expression

Example: $ expr 15 * 5

  • factor Command:

It is used to display the prime factors of a number. The syntax is $ factor number

Example: $ factor 18

  • find Command:

It searches for files in the directory and its subdirectories. The syntax is $ find directory filename

Example: $ find /home/add/ -name product.txt

  • grep Command:

It searches for a specified pattern in the file and displays the output as lines containing that pattern. The syntax is $ grep

Example: $ grep ‘linuxcent’ domain-list.txt

  • groups Command:

Shows all names of groups of a user. The syntax is $ groups

  • gzip Command:

It helps to compress a file and replaces it with one having a .gz extension. The syntax is gzip filename

Example: $ gzip passwds.txt

  • gunzip Command:

It expands or restores files compressed with the gzip command. The syntax is $ gunzip gzfilename

Example: $ gunzip sum.gz

  • head Command:

It is helpful to display the first 10 lines of the specified file or stdin to the screen. The syntax is $ head

  • hostname Command:

This command is useful to print or set the system hostname. The syntax is $ hostname

Example: $ hostname New_hostname

  • id Command:

It shows user & group information for the current user or specified user. The syntax is $ id username

Example: $ id linuxcent

  • ifconfig Command:

It is used to configure Linux system network interfaces. The syntax is $ ifconfig

  • ionice Command:

This command is used to set or view process I/O scheduling class and priority of the specified process. The syntax is $ ionice process

Example: $ ionice -c 3 rm /var/logs/syslog

  • iostat Command:

iostat command is helpful to show the CPU and i/o statistics for devices and partitions. The syntax is $ iostat

  • ip Command:

It is used to display or manage devices, routing, policy routing, and tunnels. The syntax is $ ip addr

  • iw Command:

This is used to manage wireless devices and their configuration. The syntax is $ iw

Example: $ iw list

  • killall Command:

It kills a process with the help of its name. The syntax is $ killall processname

Example: $ killall process1

  • kmod Command:

It is useful to manage Linux kernel modules. To list all currently loaded modules, type. Syntax is $ kmod

Example: $ kmod list

  • last Command:

It displays a list of last logged in users. The syntax is $ last

  • ln Command:

This is used to create a soft link between files using -s flag. Syntax is $ ln -s file1 file2

Example: $ ln -s product multiplication

  • locate Command:

It is used to find a file with its name. The syntax is $ locate filename

Example: $ locate -b ‘add.txt’

  • lshw Command:

It gives detailed information on the hardware configuration of the machine. The syntax is $ lshw

  • lscpu Command:

This Linux command displays the system’s CPU architecture information. The syntax is $ lscpu

  • lsof Command:

It displays information related to files opened by processes. The syntax is $ lsof processname

Example: $ lsof -u add

  • lsusb Command:

It shows information: about USB buses in the system and devices connected to them. The syntax is $ lsusb

  • md5sum Command:

This command is used to compute and print the MD5 message digest of the file.

  • more Command:

It enables to view through relatively lengthy text files one screenful at a time. The syntax is $ more filename

Example: $ more add

  • nano Command:

You can open a file using this nano command. The syntax is $ nano filename

Example: $ nano sum

  • netstat Command:

It displays useful information such as routing tables, network connections, and others about Linux networking subsystems. Syntax is $ netstat

Example: $ netstat -a | more

  • nproc Command:

It shows the number of processing units present to the current process. The syntax is $ nproc

  • passwd Command:

This command is used to create/update passwords for user accounts. The syntax is $ passwd username

Example: $ passwd user1

  • pstree Command:

It displays running processes as a tree that is rooted at either PID or init if PID is omitted. The syntax is $ pstree

  • reboot Command:

This command is used to power-off, halt, or reboot a system. The syntax is $ reboot

  • scp Command:

It enables you to securely copy files between hosts on a network. Syntax is $ scp

Example: $ scp ~/names.txt root@192.168.56.10:/root/names.txt

  • shutdown Command:

It schedules a time for the system to be powered down. Its syntax is $ shutdown

Example: $ shutdown –poweroff

  • sleep Command:

This command is used to pause or delay for a specific amount of time. The syntax is $ sleep

Example: $ check.sh; sleep 5; sudo apt update

  • sort Command:

This is used to sort lines of text in the specified files from stdin. The syntax is $ sort

Example: $ sort add.txt

  • split Command:

It is used to split a large file into smaller pieces. The syntax is $ split filename

Example: $ split add

  • stat Command:

It is helpful to know the file system status. The syntax is $ state filename

Example: $ stat -f add.txt

  • su Command:

It is used to switch to another user ID or become root during a login session. The syntax is $ su

  • sum Command:

This command shows the checksum and blocks counts for all files on the command line. The syntax is $ sum output filename

Example: $ sum output add.txt

  • tac Command:

It concentrates and displays files in reverse. It prints each file to the standard output, shows the last line first. The syntax is $ tac filename

Example: $ tac sum.txt

  • tail Command:

It displays the last 10 lines of each file. The syntax is $ tail filename

Example: $ tail sum.txt

  • talk Command:

talk is used to talk to another network user/ system. Use a login name to talk to the user on the same machine and use ‘use@host’ to talk to a user on another machine. The syntax is $ talk

Example: $ talk person [ttyname] or $ talk ‘user@host’ [ttyname]

  • tee Command:

This is used to read from standard input & prints to standard output and files.

Example: $ echo “Testing how tee command works” | tee file1

  • time Command:

This command runs programs and summarizes system resource usage. The syntax is $ time

  • touch Command:

It changes file timestamps and it is used to create a file. The syntax is $ touch filename

  • uname Command:

It displays system information such as operating system, network node hostname kernel name, version, and release, etc. Syntax is $ uname

  • uniq Command:

It displays or omits repeated lines from input. The syntax is $ uniq

  • uptime Command:

It shows how long the system has been running, the number of logged on users, and system load averages. The syntax is $ uptime

  • wall Command:

This command is used to send/display a message to all users on the system. The syntax is $ wall “message”

Example: $ wall “This is Linux operating system”

  • wc Command:

This command displays the word, newline, and byte counts for each file. The syntax is $ wc filename

Example: $ wc add.txt

  • whatis Command:

It searches & shows a short or one-line manual page description of the provided command name. The syntax is $ whatis wget

  • who Command:

It shows details about users who are currently logged in. The syntax is $ who

  • which Command:

This command is used to get the absolute path of the file which would be executed in the current environment. The syntax is $ which who

  • whereis Command:

It helps to locate binary, source and manual files for commands. The syntax is $ whereis cat

  • yes Command:

This command is used to display a string repeatedly until when terminated or killed. The syntax is 4 yes

Example: $ yes “This is LinuxCent – Linux HowTos”

  • zcmp/zdiff Command:

zcmp and zdiff minimal utilities used to compare compressed files. Syntax is $ zcmp filesnames, $ zdiff filesnames

Example: $ zcmp domain-list.txt.zip basic_passwords.txt.zip

$ zdiff domain-list.txt.zip basic_passwords.txt.zip

  • zip Command:

It is simple & easy to use utility used to package & compress files. Syntax is $ zip packagename

Example: $ zip inarchive.zip foo.c bar.c –out outarchive.zip

We have mentioned all the Linux commands in the Linux Commands Cheatsheet. Make use of these countless commands that you might feel helpful.

VI Basic Commands for UNIX in Nutshell

In this chapter, we will explore vi – the excellent Unix editor. There are many ways to edit text files in Unix; however, one of the best is using screen-oriented editors like vi who allow you to see context lines around a line that needs editing.

VIM, or Vi IMproved (commonly shortened to vim) is an improved version of the vi editor. It has rapidly grown in popularity because it can be used as both a command line and graphical interface text-editor with more features than standard vi that you might not find elsewhere like syntax highlighting and multitasking capabilities.

  • It’s usually available on all the flavors of Unix system.
  • Its implementations are very similar across the board.
  • It requires very few resources.
  • It is more user-friendly than other editors such as the ed or the ex.

VI Basic Commands for UNIX in Nutshell

Vi has 3 basic modes of operation: command (default), input, last line mode.

VI Editor Command mode

In command mode, you can run commands to search, copy, move, remove text.

VI Editor Input mode

In input mode, you can insert text into the file. Everything you type will be interpreted as text. many ways how to activate input mode (vi is case sensitive):

  • i – Inserts text before the cursor.
  • I – Inserts text at the beginning of the line.
  • o – Opens a new blank line below the cursor.
  • O – Opens a new blank line above the cursor.
  • a – Appends text after the cursor.
  • A – Appends text at the end of the line.

VI Editor Last line mode

To get into the last line mode type ‘:’ only from command mode. After type ‘:’ you will see a colon character appear at the beginning of the last line of your vi editor. It means vi is ready for type a “last line command”. To end vi type ‘q’ from last line mode.
You can return to command mode from input or last line mode pressing Esc.

Moving the Cursor

Key Cursor movement
w Forward one word.
b Back one word.
e To the end of the current word.
$ To the end of the line.
0(zero) To the beginning of the line.
^ To the first non-whitespace character on the line.
G Goes to the last line of the file.
IG Goes to the first line of the file.
Ctrl + F Pages forward one screen.
Ctrl + B Pages back one screen.
Ctrl + D Scrolls down one-half screen.
Ctrl + U Scrolls up one-half screen.
Ctrl + L Refreshes the screen.

Text-Deletion Commands

Command Function
R Overwrites or replaces characters on the line at and to the right of cursor. To terminate press Esc.
C Changes or overwrites characters from cursor to the end of the line.
s Substitutes a string for a character at the cursor.
x Deletes a character at the cursor.
dw Deletes a word or part of the word to the right of the cursor.
dd Deletes the line containing the cursor.
D Deletes the line from the cursor to the right end of the line.
:n, nd Deletes lines n-n. Example :2,80d deletes lines 2-80.

Text-Changing Commands

Command Function
cw Changes or overwrites characters at the cursor location to the end of that word.
r Replaces the character at the cursor with one other character.
J Join the current line and the line below.
xp Transposes the character at the cursor and the character to the right of the cursor.
~ Changes the case of the letter, either uppercase or lowercase, at the cursor.
u Undo the previous command.
. Repeats the previous command.

Text-Replacing Commands

Command Function
/string Searches forward for the string from the cursor.
?string Searches backward for the string.
n Searches for the next occurrence of the string. Use this command after searching for a string.
N Searches for the previous occurrence of the string. Use this command after searching for a string.
:%s/old/new/g Searches for the old string and replaces it iwth the new string globally.

Copy and Paste Commands

Command Function
yy Yanks a copy of the line
p Puts yanked or deleted text under the line containing the cursor.
P Put
:n,n co n Copies lines n-n and puts them after line n. Example: 1, 5 co 8 copies lines 1-5 and puts them after line 8.
:n,n m n Moves lines n-n to line n.
Example: 1,5 m 8 moves lines 1-5 to line 8.

File Save and Quit Commands

Command Function
:w Saves the file with changes by writing to the disk
:w new_file Writes the contents of the buffer to new_file.
wq Saves the changed file and quits editor vi.
😡 Saves the changed file and quits editor vi.
ZZ Saves the changed file and quits editor vi.
:q! Quits without saving changes.

Customizing vi Session

Command Function
:set nu Shows line numbers.
:set nonu Hides line numbers.
:set ic Instructs searches to ignore cases.
:set noic Instructs searches to be case-sensitive.
set list Display invisible characters.
:set showmode Display the current mode of operation.
:set noshowmode Turns off the mode of operation display.
:set Displays all the vi variables that are set.
:set all Display all vi variables and their values.

Customizing vi Session
To automatic customization for all vi sessions do the following steps:

  • Create a file in your home directory named ‘ . exrc’
  • Enter any of the set variables into the ‘ . exrc’ file.
  • Enter each ‘set variable’ command on one line.

Vi reads ‘exrc’ file every time before starting vi sessions.

Command Function
:set nu Shows line numbers.
:set nonu Hides line numbers.
:set ic Instructs searches to ignore case.
:set noic Instructs searches to be case-sensitive.
set list Display invisible characters.
:set showmode Display the current mode of operation.
:set noshowmode Turns off the mode of operation display.
:set Displays all the vi variables that are set.
:set all Display all vi variables and their values.

Bash How to Add to Array

Bash How to Add to Array

If you want to add a new item to the end of the array without specifying an index use:

~]$ my_array=()
~]$ my_array+=("Arch")
~]$ echo ${my_array[@]}
Arch

In our previous article Bash How to Print Array, we have already seen the array creation, accessing the array elements and getting the count of array.

The array is created and can be verified as follows:

$ declare -p my_array
declare -a my_array=([0]="Arch")

Now we add another element to the my_array:

my_array+=("Debian")
declare -p my_array
declare -a my_array=([0]="Arch" [1]="Debian")

Using declare to check the BASH variables

Now in order to find out the number of elements within our array, you can use “#” to get the index count, The indexed elements count are as follows for 2 element array:

echo ${#my_array[@]}
2

To add the elements to the end of the array you can use this technique demonstrated as follows:

As your array is sequential list, To insert the element to the last index, This is done by getting the total count of elements and adding that as the index:

my_array[${#my_array[@]}]="Fedora"

Now the 3rd element “Fedora” is inserted to the end of array

echo ${my_array[@]}
Arch Debian Fedora

as you already understood that “${#my_array[@]}” gets the length of the array.

Using this technique you can append arrays and also assign them to a new array as demonstrated in the following example:

new_array=(${my_array[@]} "Ubuntu")
echo ${new_array[@]}
Arch Debian Fedora Ubuntu

This is how the elements inside the new array are stored:

declare -p new_array
declare -a new_array=([0]="Arch" [1]="Debian" [2]="Fedora" [3]="Ubuntu")

Bash How to Print Array

Bash How to Print Array

Arrays are collection of elements, The Arrays in bash are indexed from 0 (zero-based).
Below is the definition on an Array in Bash
my_array=(zero one two three four)

Now our array is defined.
Here is exactly how the my_array is stored on BASH:

my_array=([0]="zero" [1]="one" [2]="two" [3]="three" [4]="four")

You can explicit define an array:

declare -a MY_ARRAY

You can view the declarations along with other environment variables using the declare command.

declare -p my_array
declare -a my_array=([0]="zero" [1]="one" [2]="two" [3]="three" [4]="four")

Now if you try to print the array:

my_array=(zero one two three four)
echo $my_array
zero

By default only the first element value is printed which belongs to the 0 index.

To print the first element of the array using the indexing:

my_array=(zero one two three four)
echo ${my_array[0]}
zero

The change we noticed here is the use of the Curly Braces ‘{}’, its used to refer to the value of an item in the array. The curly braces are required to avoid issues with path name expansion.

To read all elements of the array use the symbols “@” or “*”.

echo ${my_array[@]}
zero one two three four
echo ${my_array[*]}
zero one two three four

The difference between “$@” and “$*” is “$@” expands each element as a separate argument, however “$*” expand to the arguments merged into one argument.

To prove this, print the index elements followed by $@ or $* format.

echo ${my_array[$*0]}
zero
echo ${my_array[$@1]}
one
echo ${my_array[$*2]}
two

Getting the Length of the Array

If you need to get the length of the array uses the symbol “#” before the name of the array:

echo "${#my_array[*]}"
5

What is Fork Bomb and How to Avoid It

What is Fork Bomb and How to Avoid It

The fork bomb is a recursive bash function. It is a DoS attack against linux operating system. Definition of fork bomb:

:(){ :|:& };:

What do all these symbols mean?

  • :() – defines function called “:”
  • :|: – recursive sends output to “:”
  • & – puts function to background
  • ; – terminate the function definition
  • : – at the end calls the function

Be careful this example may crush your computer. We can prevent against fork bomb limiting the number of processes for user (or group of users) in file /etc/security/limits.conf.

For example, we want to limit the number of process to 300:

likeIT hard nproc 30

“likeIT” is name of user. If you want to apply this limitation to the group, use “@groupName”.

There is an example of the whole configuration file:

Let’s explain some important keywords from /etc/security/limits.conf file:

[domain] [type] [item] [value]

The domain can be:

  • a user name
  • a group name – use @group syntax

Type can have these two values:

  • soft – for enforcing the soft limits
  • hard – for enforcing hard limits

Item can be:

  • core – limit the core file size (KB)
  • fsize – maximum filesize (KB)
  • cpu – max CPU time (MIN)
  • nproc – max number of processes