Scripts – listdevs.bash

Print Friendly, PDF & Email

DISCLAIMER

This script is as is. I give no warranty it will work as you expected on your system. You are running it at your own risk. If something goes wrong because of this script, I bear no responsibility.

Language


server# bash -version
GNU bash, version 3.2.52(1)-release (sparc-sun-solaris2.10)
Copyright (C) 2007 Free Software Foundation, Inc.

Purpose

You know a list of comma separated hexadecimal device ids (range as well as solo), and want to print them one per line. listdevs.bash will do it for you. I use this frequently while preparing a flat file containing pairs of rdf devices.

Usage


server# listdevs.bash 1A4,1234:1236,1ab
01A4
01AB
1234
1235
1236

server# cat list_devs.bash
#!/bin/bash
#
# A script to list the device ids on a screen when the input is range of devices separated by ","
# Author - Ketan Patel
# To run: list_devs.bash 1234:1245,1a0:1b0

# Make sure arguments are given
if [ $# -eq 0 ]; then
echo "No arguments found. Supply device id ranges separated by commas. Example: list_devs.bash 1234:1245,1a0:1b0"
exit
fi

# Read the given argument and save them into array after splitting them using "," as delimitor
IFS="," read -a ranges <<< "$@"

# Function h2d to convert hexadecimal to decmal
function h2d {
  echo "ibase=16; $@"|bc
}

# Function d2h to convert decimal to hexadecimal
function d2h {
  echo "obase=16; $@"|bc
}

# Go through each element of the array and start displaying on the screen
for range in "${ranges[@]}"
do
  # Check whether it is a range separated by : or just a single device
  if [[ "$range" =~ ":" ]]; then
    # Split the string delimeted by : and save first and last dev after converting them into upper case
    IFS=":" read -a first_and_last <<< "$range"
    firsthex=`echo ${first_and_last[0]} | tr "[:lower:]" "[:upper:]" `
    lasthex=`echo ${first_and_last[1]} | tr "[:lower:]" "[:upper:]" `

    # Convert first and last numbers into dec
    firstdec=`h2d $firsthex`
    lastdec=`h2d $lasthex`

    # Check the range - make sure first dev is less than last dev
    if [ $lastdec -lt $firstdec ]; then
      echo "Range given is incorrect - last number is smaller than first number"
      exit
    fi

    # For numbers between the firstdec and lastdec, print the hex on screen
    for ((i=$firstdec;i<=$lastdec;++i))
    do
      echo `d2h $i`
    done
  else
    # Only a single device is given, convert into upper case, and print it out
    firsthex=`echo $range | tr "[:lower:]" "[:upper:]" `
    echo $firsthex
  fi
done

,

sanaswati
No comments yet.

Leave a Reply

*