bashhp-ux

HP - UX - Size calcucation using bash script


I am trying to display size in human-readable form on HP-UX. We have a few legacy systems which we use for sftp transfers. These servers are connected T1 leased line and transfers are very slow. I have to occasionally check the size to verify if the transfer is done or not. As HP-UX cant display the size in kb or GB, we have to manually divide the output to verify. I am just trying to build a small script to display the size in GB.

read -p "Enter File Path/Location " location
output=$(ls -l $location | cut -d ' ' -f 18)
#output=$(ls -l /central/home/sftp/file.daily | cut -d ' ' -f 18)
echo "Size in GB is:  ${output}"
#echo "Size in GB is:  ${output} / (1024*1024*1024)"  not working "

bash-4.4$ ./script
Enter File Path/Location /central/home/sftp/file.daily
Size in GB is:  153844074
bash-4.4$ 

Guys/Gals, I am not a pro, just learning stuff to enhance my knowledge in bash scripting.


Solution

  • Your command echo "Size in GB is: ${output} / (1024*1024*1024)" is not working because the expression is just a string. To do calculations in bash, use an arithmetic context $(( ... )). However, bash cannot handle floating point numbers, therefore I'd resort to bc.

    Also, ls | cut -f 18 seems a bit strange. This would retrieve the 18th field. The output of my ls -l has only 9 fields and the file size is the 5th field.
    Instead of parsing ls you can parse du, which is simpler and less error prone. du -k prints the size in kB (= 1024 Byte).

    #! /usr/bin/env bash
    size_kB=$(du -k "$1" | cut -f 1)
    size_GB=$(echo "scale=1; $size_kB / 1024 / 1024;" | bc)
    echo "File $1 has size $size_GB GB"
    

    Store this script in a executable file, then use it as

    bash$ path/to/myscript.sh someFile
    File someFile has size 12.3 GB
    

    Passing the filename as an argument allows you to use tab completion. This wouldn't have been possible with read.