Bash

From XennisWiki
Jump to: navigation, search

Bash is a Unix shell written by Brian Fox for the GNU Project as a free software replacement for the Bourne shell. Released in 1989, it has been distributed widely as the shell for the GNU operating system and as a default shell on Linux and Mac OS X. It has been ported to Microsoft Windows [...]. (Wikipedia)

Basic commands

Condition

if [ CONDITION ]; then
	[...]
elif [ CONDITION ]; then 
	[...]
else
	[...]
fi

For instance check if a file exists and then source it (see also: File test operators

if [ -f '~/bash_example' ]; then
    source '~/bash_example';
fi

Case distinction

case "$1" in
"example")
	[...]
	;;
"test")
	[...]
	;;
*)
	echo "default"
	;;
esac

Loop

Further information: Bash While Loop Example

while [ CONDITION ]
do
	[...]
done

For loop over a string array

declare -a example=(red, green, blue)
for i in ${example[@]}
do
	echo $i
done

Function

Further information: Bash Shell Script Function Examples

print_word(){
	local word=$1
	echo $word
}

print_word Hello

Date and time as variable

Outputs for instance 2017-04-05T14:31:16

timestamp=`date +%Y-%m-%dT%H:%M:%S`
echo $timestamp

More

Output

echo "Hello"

Wait ten seconds (Further information: Bash Script Sleep or Delay a Specified Amount of Time)

sleep 10

Commands

No output and error

exampleCommand &> /dev/null

Check return code

exampleCommand
return_code=$?
if [ $return_code -eq 0 ]; then
    echo "success"
fi

Exit on first failure

set -e

Current timestamp

Further information: Bash - Scripts

timestamp=`date +%s`
echo $timestamp

Set terminal title from command line

echo -en "\033]0;My title\a"

Escape a single quote

$ echo 'some'"'"'string that is $ properly escaped `'
some'string that is $ properly escaped `

Examples

More Bash scripts you find in the article Bash - Scripts.

Simple script

#!/usr/bin/env bash
BASEDIR=`dirname $0`

if [ "$#" -lt 1 ]
then
	echo "Usage $1 [test|example]"
	echo "Example: $0 test"
	exit 1
fi

PROPERTIES_FILE="../example.txt"

case "$1" in
"test")
	echo "$1 (bash $0 example)"
	bash $0 example
	;;	
"example")
	echo "$1 (grep $PROPERTIES_FILE)"
	grep 0x0A $PROPERTIES_FILE
	;;
esac

Configurations file

Configurations file example.cfg

TEST="Hello"
APP="World"

Include file in the script

source example.cfg

echo $TEST

Single line for loop

for i in {01..10}; do echo $i; done
for i in `seq -w 01 10`; do echo $i; done

See also

External links