• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 700
  • Last Modified:

Issue with Linux Bash Script function command

Hi Guys,

I'm having an issue with my Bash script where I want to create a function called test and run commands using that function so would not have to keep writing it over and over. Can someone tell me how I can fix my script below to do that? I'm also trying to display either the Green OK when the statement has successfully completed and Red Failed when it has not. I also would like the output of the entire script to be sent to a custom made log file. Does anyone know how i can accomplish all of this?

Thanks so much!

#!/bin/bash

. /etc/init.d/functions

function test {
"$@"
if [ $? == 0 ]
then
     echo [ "The File is there" ] && echo_success
else
     echo "The File is not there"
fi
}

test mount | grep "on /tmp" > /dev/null 2>&1
test mount | grep "on /var" > /dev/null 2>&1

Open in new window

0
Tbalz
Asked:
Tbalz
1 Solution
 
omarfaridCommented:
try to name the function other than test since test is acommand
0
 
TbalzAuthor Commented:
That didn't work but thanks
0
 
woolmilkporcCommented:
1) You must use

eval "$@"

in line 6 so the shell will "evaluate" the command string (i.e. execute it as a whole instead of resolving things like | or > prematurely).

2) You must enclose the string passed to the function in quotes (best use single quotes) so that it gets passed to the function "as is" (i.e. things like |, > are evaluated inside the function by "eval" and not by the shell before passing the parameter to the function).

test 'mount | grep "on /tmp" > /dev/null 2>&1'

3) Avoid naming a function "test", because it's a shell builtin, although "bash" will tolerate it (functions take precedence over builtins), but e.g. "ksh" doesn't tolerate it.

As for the colours: You could use ANSI colour escape codes:
http://bluesock.org/~willg/dev/ansi.html
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now