Bash How to Echo Quotes

Bash How to Echo Quotes

In this case, it is essential to put a backslash. Backslash will focus on character followed by a sign with a backslash. The following characters depose functions of the meta tag.

If you want to echo single quotes, you can to:

echo Single quote: \'

Output: Single quote: ‘

If you want to echo double quote, you can do:

echo Double quote: \"

Output: Double quote: ”

If you want to quote a single quote in double-quotes:

echo "Single quote in double-quotes: '"

Output: Single quote in double-quotes: ‘

If you want to quotes double quotes in double-quotes:

echo "Double quote in double-quotes \""

Output: Double quote in double quotes ”

There are 2 kinds of quoting: weak (“) and strong (‘). Using weak quoting there is no special meanings of:

  • pathname expansion
  • process substitution
  • single-quotes
  • characters for pattern matching

If we use strong quoting, nothing is interpreted, except a single quote. Examples:

echo "Path to your shell is: $SHELL"
echo 'Path to your shell is: $SHELL'

Output: Path to your shell is: /bin/bash
Path to your shell is: $SHELL

Bash How to Stop Script

Bash How to Stop Script

If you want to stop the bash script, that is currently running, you can do the following sentence in bash:

kill $(ps aux | grep name_of_scirpt | grep -v grep | awk '{ print $2 }')

Command ps aux will give you all processes that are currently running. Grep will filter the name that you want to kill. You should be very specific, in another word, the whole name of the process name should be used here. Grep -v grep will filter grep process. AWK will filter the second column from the output, that is PID (process id).

If you want to stop script on a specific line, just add

exit 45

This line exits your script and gives 45 to the parent process. You can choose a number between 0 – 255. Number 0 is special, it means that your script exits without any problem. Any number between 1 – 255 means that something wrong happens in your script.

If you want to stop your script, if 1st error occurs, just add in hashpling line (1st line of the script) -e parameter:

#!/bin/bash -e
...
command1
command2
command3

This script will terminate immediately if some line fails. What means that line of the script fails? It means that line will exit with a non-zero exit code (1-255). For example, if command2 fails (return non-zero exit code), command3 will not be executed, at all.

I love this option in a test environment. It helps me to avoid unnecessary script execution after failure. I also like the bash -u parameter that exits your script if you use an uninitialized shell variable.

If you want to get the exit code of the last command enter:

echo $?

Bash will print integer values between 0 and 255.

Bash How to Assign Output to Variable

Bash How to Assign Output to Variable

Backquotes (“) are used for command substitution.

var=`date`

Command “date” return date to variable “var”. The alternative method to using command substitution is “$()”:

var =$(date)

If we want to get value from “var” use “$var”:

echo "$var"

Output: Tue Jul 12 15:33:06 CEST 2016

It properly always uses double quotes around variable substitution. Without double quotes, the variable is expanded which may cause problems if the variable contains special characters.

Make sure there is no space between variable name before and after assign char (=). You can assign output from pipeline to a variable:

NUM_FILES=`ls | wc -l`

Bash Yes to All

Bash Yes to All

Do you remember when Homer Simpson worked at home? Long did not enjoy it. Therefore he is represented by birds, which automatically screen by pressing the “y” key. How could this be done in BASH?

Yes command inserts the “y” character of STDIN infinitely times.

yes

You can use it in way of STDIN redirection to another command:

yes y | command

Let’s write a small script, that will expect three lines of text from you:

#!/bin/bash
read AAA
read BBB
read CCC
echo "$AAA, $BBB, $CCC"

Now, try to execute our script with yes in pipe:

yes | ./read.sh

If you want o give the opposite answer to our script, it is possible. Just pass string argument to yes:

yes n | ./read.sh

If script expects capital ‘Yes’ use:

yes Yes | ./read.sh

Some commands have an “assume-yes” flag ‘-y’, for example: yum, apt-get.

Bash How to Check If File Exists

Bash How to Check If File Exists

What is the definition file in Linux? The file is almost everything – keyboard, and disk, and the regular file. Here is an example of a regular file: document.odt or /etc/passwd.

If you want the script to find out if there is any file (eg. tile.txt or /dev/sda), you can do the following:

if [ -e /root/file.txt ]; then
echo "File found";
fi

So, we tested if any kind of file (named /root/file.txt) exists.

If you want to take into consideration just regular files (not /dev/sda but just /root/file.txt), you can use -f parameter instead of -e parameter:

if [ -f /root/file.txt ]; then
echo "Regular file found";
fi

If you want to check, if a regular file not exists, you can use not(!) in test command []:

if [ ! -f /root/file.txt ]; then
echo "Regular file not found";
fi

We could tune the last example. You can also use short way how to write it:

[ ! -f /root/file.txt ] && echo "Regular file not found"

It is my favorite if you have just one command after the test command.

Here are some examples of file test operators:

Option Test
-s File is a regular file (if the file is directory or device returns false)
-d File is a directory
-b File is a block device
-c File is a character device
-p File is a pipe
-w File has a write permission

 

Bash Vs KSH

Bash Vs KSH

Linux and Unix have various shells. Two kinds of these numerous shells are KSH and BASH.

KSH (The Korn Shell) was developed many years before the BASH. Ksh has associative arrays and handles loop syntax better than bash. Also, ksh’s command print is better than bash’s echo command. In other way, ksh does not support history completion, process substitution, and rebindable command-line editing.

Bash has more added extension than ksh. Bash has tab completion and an easier method to set a prompt in order to display the current directory.

Compared to ksh, bash is newer and more popular.

Example of difference ksh and bash in condition test. First bash:

if [ $i -eq 3 ]

and condition test in ksh:

if (($i==3))

Bash can handle exit codes from pipes in a cleaner way. Bash and KSH are both Bourne=compatible shells, they share common functions and features and can be interchangeable to use.

Bash How to Quit a Script

Bash How to Quit a Script

The command “exit” terminate the script and return value:

Every command returns an exit status, sometimes it is called exit code or return status.

0: Script was executed with success.

1 and greater: Script was executed with error. The non-zero return value is interpreted as an “error code”.

If you want to get the exit value last executed script use $?.

./script.sh
echo $?

Sometimes you can see exit $? which is equivalent to exit.

Bash How to get Yesterday’s Date

Bash How to get Yesterday’s Date

Date command has d parameter, that displays time described after d parameter:

date -d yesterday '+%Y-%m-%d'

%Y means year, %m means month, and %d means day. You can change formatting if you want:

date -d yesterday '+%Y:%m:%d'

What if you want get several days, for example, day before 5 days?

date +%Y-%m-%d -d "5 day ago"

Would you take yesterday’s date to the variable?

YESTERDAY=`date -d yesterday '+%Y-%m-%d'`
echo $YESTERDAY

Alternative way is using hours:

date -d "24 hours ago" '+%Y-%m-%d'

Another way:

date --date='-1 day' '+%Y-%m-%d'

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.