Bash How to Echo Array

Bash How to Echo Array

You can define three elements array (there is no space between the name of an array variable, equal symbol, and starting bracket):

FILES=(report.jpg status.txt scan.jpg)

This command will write each element in the array:

echo ${FILES[*]}

Index in shell arrays starts from 0. So, if you want to write just the first element, you can do this command:

echo ${FILES[0]}

Output: report.jpg

Do you want to process each element in the array in the loop? Here is an example:

for ELEMENT in ${FILES[@]}
do
echo File: $ELEMENT.
done

If you want to get only indexes of the array, try this example:

echo ${!FILES[@]}

“${!FILES[@]}” is a relatively new bash feature, it was not included in the original array implementation.

Bash Error Output

Bash Error Output

Bash provides I/O redirection. There are 3 standard files: STDIN (standard input) with descriptor 0, STDOUT (standard output) with descriptor 1, and STDERR (standard error) with descriptor 2.

If you want to redirect your messages to STDERR, you can use >&2 symbol. This symbol is abbreviation of 1>&2 symbol which means, that everything in STDOUT will go to STDERR.

So, if you want to put the message “Cannot delete directory” in STDERR, you can do it this way:

echo Cannot delete directory >&2

Even more, you might to create your own function for error messages:

recho() { echo "$*" >&2 ; }
recho "Cannot delete directory" > /dev/null

Output: Cannot delete the directory

On the first line, we define recho function (error echo). This function will print all its arguments ($*) to STDERR (>&2).

On the second line, we try to use the function. To prove, that output will be written to STDERR, we will redirect STDIN to nowhere (/dev/null). So, if you see some output, it should be in STDERR.

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'

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