Bash - Scripts

From XennisWiki
Jump to: navigation, search

This article contains some Bash scripts.

Simple scripts

Time (Unix timestamp)

Unix timestamp as decimal and hexadecimal

date +%s
printf "0x%x\n" $(date +%s)

Unix Zeitstempel as hexadecimal and as hex byte

UTC=$(date +%s)
UTC_HEX=$(printf "%x\n" $UTC)
UTC_HEX_BYTE=0x${UTC_HEX:0:2},0x${UTC_HEX:2:2},0x${UTC_HEX:4:2},0x${UTC_HEX:6:2}

echo $UTC_HEX
echo $UTC
echo $UTC_HEX_BYTE

Output

51979698
1368888984
0x51,0x97,0x96,0x98

Ask yes / no question

see davejamesmiller - ask.sh

Display menu from files

Displays all .sh files in the directory software as a selecting menu.

PS3='Please enter your choice: '
SOFTWARE=software/*.sh
select software in ${SOFTWARE[@]}
do
	echo "${software}";
done

Grep files on multiple servers

grep-apps() {
    if [ "$#" -lt 2 ]
    then
    	echo "Usage: grep-apps pattern file"
    	exit 1
    fi
    grep_pattern=$1
    file_path=$2
    color_green='\e[0;32m'
    color_reset='\e[0m'

    for i in {01..10}; do
        echo -e "${color_green}app${i} <<<<<<<<<<<<<<<<<<<<${color_reset}";
        ssh app$i.example.org grep "$grep_pattern" "$file_path";
    done
}

Download a file and check its checksum

For example download Istio

version="1.1.2"
release_file="istio-${version}-linux.tar.gz"
checksum_file="istio-${version}-linux.tar.gz.sha256"
curl --location --silent --remote-name "https://github.com/istio/istio/releases/download/${version}/${release_file}"
curl --location --silent --remote-name "https://github.com/istio/istio/releases/download/${version}/${checksum_file}"
sha256sum --check --quiet "${checksum_file}"

Check scripts

Check file / folder exits

#
# Check if file exits
#
function check_file_exits(){
    if [ "$#" -lt 1 ]
    then
        echo "Usage check_file_exits FILE"
        echo "Example: check_dir_exits example.txt"
        echo ""
        exit 1
    else
        local file="$1"
    fi

    if [ -f "${file}" ]
    then
        return 0
    else
        return 1
    fi
}
#
# Check if directory exits
#
function check_dir_exits(){
    if [ "$#" -lt 1 ]
    then
        echo "Usage check_dir_exits DIR"
        echo "Example: check_dir_exits dir/"
        echo ""
        exit 1
    else
        local dir="$1"
    fi
 
    if [ -d "${dir}" ]
    then
        return 0
    else
        return 1
    fi
}

Check package is installed (Ubuntu)

#
# Uses dpkg to check if a package exits / is installed.
#
function check_package_exits() {
	if [ "$#" -lt 1 ]
	then
		echo "Usage check_package_exits PACKAGE-NAME"
		echo "Example: check_package_exits vim"
		echo ""
		exit 1
	else
		local package_name=$1
	fi
	
	if dpkg -l | grep -qw ${package_name};
	then
		return 0
	else
		return 1
	fi
}

See also