Bash / Shell Basics

Working with Strings in bash.

How to extract the hostname from a FQDN String

For example: host1.example.com


#!/bin/bash
FQDN=host1.example.com

# Use cut and . as delimiter. 
HOST=$(echo $FQDN | cut -d '.' -f 1);
HOST=`echo $FQDN | cut -d '.' -f 1`
DOMAIN=$(echo $FQDN | cut -d '.' -f 2-)

# Alternative: bash include shell functions
HOST=${FQDN%%.*}
DOMAIN=${FQDN##/.*}
echo "Hostname: ${HOST}, Domain: ${DOMAIN} of FQDN: $FQDN"

Extract Filename and Path.


#!/bin/bash
FILE="/home/user/document.xml"
FILENAME=${FILE##*/}
PATH=${FILE%/*}
TYPE=${FILE##*.}

echo "File Name: ${FILENAME} in path: ${PATH} of type ${TYPE}";