Linux Ask!

Linux Ask! is a Q & A web site specific for Linux related questions. Questions are collected, answered and audited by experienced Linux users.

Split on specific characters on Bash Script's for loop

Answer:

If you want to Bash script's for loop to split on non white-space characters, you can change the IFS, e.g.

#!/bin/bash
IFS='-'

list="a-b-c-d-e"

for c in $list; do
    echo $c
done

The above script will split on the character '-'

E.g.

# ./test.sh

a
b
c
d
e

Check if a file exist in Bash Shell

Answer:

The following script demonstrates how to check if a file exist, using shell (Bash) script

#!/bin/bash

if [ -e test.txt ]
then
  echo 'The file exists.'
else
  echo 'The file does not exist.'
fi

How to echo string to standard error (stderr)?

Answer:

To echo string to the standard error (stderr), rather than the standard output (stdout), you can define the following function in your shell (put in your ~/.bashrc file)

# function echo2() { echo "$@" 1>&2; }

Then you can execute the command like:

# echo2 test

Simple for loop in Bash shell

Answer:

A simple for loop in Bash shell would like the following. You can use it wisely to skip a lot of repetitive tasks.

#!/bin/bash

for i in {1..10}
do
   echo "I am command No. $i"
done

How to echo a tab in bash?

Answer:

In Bash script, if you want to print out unprintable characters such as tab, you need to use -e flag together with the echo command.

E.g.

echo -e "\tfoo\tbar"