Looks like no one’s replied in a while. To start the conversation again, simply ask a new question.

Relative "newbie" question about a a function call

Hi all,
I am following along in "Learning Bash" and cannot get page 105 to work for me. (function call).
So, tried this little experiment, which leaves me stuck.
In the current directory, I have a script "myStack" as follows.

#! /bin/bash

test()
{
echo "Hello world"
}


I call it thus: (the current directory has been added to PATH)

myStack test

expecting to see "Hello World".

( Have tried myStack test(), also using a variety of quoting options)

I get no error, but get the prompt back with no text.

Anyone to the rescue?? 🙂

Thank you

Mac Pro, Mac OS X (10.6.5)

Posted on Jan 30, 2011 9:43 AM

Reply
4 replies

Jan 30, 2011 10:17 AM in response to pi22-7__

Your script doesn't do anything. It creates an internal function which is never called, then exits. The function is not a command-line argument, it is a re-usable piece of code for use inside the script. Call the function inside the script, like this:

#!/bin/bash
test() {
echo "Hello world"
}
# Call the test function:
test


Or, another example that reuses the function:

#!/bin/bash
test() {
echo "Goodnight, "$1
}
# Call the test function twice:
test world
test moon

Jan 30, 2011 4:42 PM in response to pi22-7__

Side note. When posting code, you should wrap it in a pair of
tags

...
... your code here ...
...

The "myStatck test" invocation passes "test' as the $1 arg.
You can access your options via $1, $2, $3, $4, ...
$0 the path used to invoke your script
You can use 'shift' to remove $1, and shift $2 into $1, $3 into $2, etc...
You can substitute all the arguments at once using $* or "$*"
You can substitute all the arguments and preserve any command line quoting using "$@", where the double quotes are important.
You can loop through all your arguments using

for arg
do
echo "$arg"
done

There are other ways to loop though the arguments, for example

while [[ X$1 = X-* ]]
do
if [[ X$1 = X-q ]]; then
OPTION qSET=1
elif [[ X$1 = X-r ]]; then
OPTION rSET=1
elif [[ X$1 = X-s ]]; then
OPTION sSET=1
else
echo 1>&2 "Oops! Unknown option: $1"
exit 1
fi
shift # remove $1 so we can check the next argument
done

for arg
do
test "$arg"
done
exit 0
{code}

Relative "newbie" question about a a function call

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple ID.