Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BASH pass Variable to Function

This is my first attempt at BASH and I am having a small problem. The intent of this script is to scrub ZFS pools and create a log file.

The code is working as intended, except for line 19 below. (LogEntry $LOG_LINE). I added Line 18 for debugging purposes and it is working.

Line 18 writes "pool 'tankm' is healthy" to the log, while line 19 only wirtes "pool". Functionally these line are doing the same thing (as least to my eyes), so why would one work and not the other.

I'm assuming the root casue is the quote before the pool name in the output of the zpool status command and I am working on a char replacement for that, but I would liek to understand how these two lines are being interprited differently.

Thanks in advance Declan

#!/bin/bash

LOG_FILE=/home/declan/log/zfs_scrub
LOG_LAST=/home/declan/log/zfs_scrub_last

function LogEntry {
    echo -e "$(date "+%Y %m %d %T") ; $1" >>$LOG_FILE 2>&1
}

cp $LOG_FILE $LOG_LAST
rm $LOG_FILE

LogEntry "Starting ZFS Scrub"

for POOL in $(zpool list -H -o name) ; do
    LogEntry "Starting Scrub on $POOL"
    zpool scrub $POOL 2>/dev/null
    LOG_LINE=$(zpool status -x $POOL 2>&1)
    echo -e "$(date "+%Y %m %d %T") ; $LOG_LINE" >>$LOG_FILE 2>&1
    LogEntry $LOG_LINE
    LogEntry "Ending Scrub on $POOL"
done

LogEntry "Ending ZFS Scrub"
like image 739
Declan_K Avatar asked Apr 26 '13 15:04

Declan_K


2 Answers

You have to add double quotes around $LOG_LINE:

LogEntry "$LOG_LINE"

Otherwise each element delimited by a whitespace is interpreted as a dedicated argument to the LogEntry function.

Alternatively you could change your function and use $* or $@ to reference all arguments:

function LogEntry {
    echo -e "$(date "+%Y %m %d %T") ; $*" >>$LOG_FILE 2>&1
}
like image 171
bmk Avatar answered Sep 27 '22 21:09

bmk


Based on what I've learned, I was even able to remove the LOG_LINE variable completely. Here's the final code.

#!/bin/bash

LOG_FILE=/home/declan/log/zfs_scrub
LOG_LAST=/home/declan/log/zfs_scrub_last

LogEntry () {echo "$(date "+%Y %m %d %T") ; $1" >>$LOG_FILE 2>&1; }

cp $LOG_FILE $LOG_LAST
rm $LOG_FILE

LogEntry "Starting ZFS Scrub"

for POOL in $(zpool list -H -o name) ; do
    LogEntry "Starting Scrub on $POOL"
    zpool scrub $POOL 2>/dev/null
    LogEntry "$(zpool status -x $POOL 2>&1)"
    LogEntry "Ending Scrub on $POOL"
done

LogEntry "Ending ZFS Scrub"
like image 41
Declan_K Avatar answered Sep 27 '22 23:09

Declan_K