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'

Bash How to Add Numbers

Bash How to Add Numbers

Bash provides a lot of methods how to add numbers. First of all is use $(())

echo $((2+2+1))

Output: 5

If we have a variable which has an integer value, we can use “$var”:

var=5
echo $((6+$var))

Output: 11

We can assign to variable counted numbers:

var=$((3+6))

The value of “var” is 9 now.

Another arithmetic expansion:
var=$((num1 + num2))
var=$(($num + $num2))
var=$((num1 + 10 + 20))
var=$[num1+num2]

Bash How to Format Date

Bash How to Format Date

The easiest way to get a date in YYYY-MM-DD is as follows:

date -I

Output: 2016-06-07

The parameter ā€œIā€ tells the date command, the ISO date format is required.

Of course, you can also use your own definition. %Y means year, %m means month, and %d means day:

date +%Y-%m-%d

Output: 2016-06-07, the same.

If you want to display also hours:minutes:second, let’s do:

date +%Y-%m-%d:%H:%M:%S

Output: 2016-06-07:17:02:19

You fill the variable date as follows:

DATE=`date +%Y-%m-%d:%H:%M:%S`

Here are some examples of format control:

  • %u – day of week(1..7), 1 is Monday
  • %w – day of week(0..6), 0 is Sunday
  • %U – week number of year, with Sunday as the first day of the week (00..53)
  • %V – week number of year, with Monday as the first day of the week (00..53)
  • %s – seconds since 1.1.1970 UTC
  • %Y – year
  • %y – last two digits of year(00..99)
  • %r – locale’s 12-hour clock time
  • %R – 24-hour hour and minute

Bash How to get Result of Command

Bash How to get Result of Command

To get the result of the command you need to use command substitution (bash feature). Command substitution provides executing a bash command/commands and store its output to a variable.

You can use special backticks (“). Everything what you write between backticks is executed by the shell before the main command is executed. Sometimes people call them back quotes. Surely you know that they’re under [Esc] key.

In this example, we get date into variables:

DATE=`date -I`
echo $DATE

If you expect multi-line output, and you would like to display it, it is good practice to use double quotes. In this example, we get all files in /etc into variable FILES:

FILES=$(ls /etc -l)
echo "$FILES"

What if you want to use backticks into backticks? It is a little trouble. The solution is to use a dollar with brackets $(). This example does the same:

DATE=$(date -I)
echo $DATE

It is also possible to use the inner way. In the next example, the output of date will be used as the first echo argument:

echo `date -I`

Bash How to Pass Array to Function

Bash How to Pass Array to Function

To pass all array items as arguments to the function using the following syntax:

my_function "${array[@]}"

To get values from the array in function use:

array_in_function=("$@")

If you would use “$1” instead of (“$@”) you get the first item from the array, “$2”-second item and etc.

Here is an example of the function “array_echo” which writes all items of the array.

function array_echo() {
arr=("$@")
for i in "${arr[@]}"; do
echo -n "$i "
done
}

array=(1 2 3 4 5 )
array_echo "${array[@]}"

Note: The “n” option in the echo command doesn’t output the trailing newline.

Actually, it is not passing an array as a variable, but as a list of its elements. In our example, you can not change values of array items from function array_echo().

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.