niXforums Forum Index
 FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   PreferencesPreferences   Log in to check your private messagesLog in to check your private messages   Log inLog in 
·  nixdoc.net ·  man pages ·  Linux HOWTOs ·  FreeBSD Tips ·  Forums
navigation Forum index » Programming » shell
Passing parameters back from a function
Post new topic   Reply to topic Page 3 of 43 [637 Posts] View previous topic :: View next topic
Goto page:  Previous  1, 2, 3, 4, 5, ..., 41, 42, 43 Next
Author Message
Stu
*nix forums addict


Joined: 22 Mar 2005
Posts: 89

PostPosted: Sat Feb 19, 2005 8:46 pm    Post subject: Re: Passing parameters back from a function Reply with quote

Barry Margolin wrote:
Quote:
In article <1108697901.614706.212320@f14g2000cwb.googlegroups.com>,
"Stu" <beefstu350@hotmail.com> wrote:

Can somebody show me the best way to pass set parameters back from
a
function within a shell script. I know the following code should
work
(see below) since parm1 and parm2 are global variables.

setit()
{
parm1="hello"
parm2="world"

}

parm1=""
parm2=""
setit parm1 parm2

At this point I would like to see $parm1="Hello"

setit ()
{
eval \$$1='"hello"'
eval \$$2='"world"'
}

--
Barry Margolin, barmar@alum.mit.edu
Arlington, MA
*** PLEASE post questions in newsgroups, not directly to me ***


I am not to sure I understand amd I missing something. Can you please
explain. Thanks

cat x.sh
#!/bin/ksh

setit()
{
eval \$$1='"hello"'
eval \$$2='"world"'
}

setit parm1 parm2

../x.sh
../x.sh[2]: =hello: not found
../x.sh[3]: =world: not found
Back to top
Janis Papanagnou
*nix forums Guru


Joined: 24 Feb 2005
Posts: 450

PostPosted: Sat Feb 19, 2005 8:46 pm    Post subject: Re: Passing parameters back from a function Reply with quote

Stu wrote:
Quote:
Can somebody show me the best way to pass set parameters back from a
function within a shell script. I know the following code should work
(see below) since parm1 and parm2 are global variables.

setit()
{
parm1="hello"
parm2="world"

}

parm1=""
parm2=""
setit parm1 parm2

At this point I would like to see $parm1="Hello"

Lets assume that setit() is in a file called y.sh and the caller is in
a file x.sh (two different files). I know I have to source in y.sh to
make the function available, and doing this will make the use of
"Global Variables" that much harder to track down that why I want to
pass them as a parmeter list and have the values in the list come back
to the caller set.

A more accurate description using "C" code would be as follows:

void
setit(int parm1)
{
*parm1=44;
return;
}

main()
{
int parm1;
setit(&parm1)
}


Am I worried about nothing ? Secondly, can what I want be done with in
KSH.

Thanks in advance to all that answer this post


Closest to your "C" code might be to use name references (if you happen
to use ksh93)...

function setit
{
typeset -n p1=$1
typeset -n p2=$2

p1="hello"
p2="world"
}

x=abc
y=def
setit x y
print - "x=$x y=$y"

Results in:
x=hello y=world


Janis
Back to top
Alan Connor
*nix forums Guru


Joined: 28 Feb 2005
Posts: 481

PostPosted: Sat Feb 19, 2005 8:46 pm    Post subject: Re: How to display the each executed line of a shell script? Reply with quote

On Wed, 9 Feb 2005 01:05:20 +0100, Matt Benson
<mbens@hotmail.com> wrote:

I am posting from comp.os.linux.misc.

Quote:
When I start (in ksh) a shell script test.sh How do I let the
shell interpreter display each line he will execute just before
he is really executing it. The display should include the real
content of variables.

Matt

comp.lang.perl.misc!? (deleted from list of newsgroups)


All this cross-posting is really going overboard.

We'll see you the next time around. (Unless you've cross-posted
to a dozen groups for something less than a system emergency.)

Scratch that. This is obviously your post too:

<quote>

Path: newsspool2.news.pas.earthlink.net!stamper.news.pas.earthlink.net
!elnk-nf2-pas!newsfeed.earthlink.net!newshub.sdsu.edu
!newsfeed00.sul.t-online.de!newsmm00.sul.t-online.de!t-online.de
!news.t-online.com!not-for-mail
From: peter_ha@andres.net (Peter Hanke)
Newsgroups: comp.os.linux.misc,comp.unix.shell,comp.unix.questions
Subject: What does the statement "exec >myfile.dat" mean?
Followup-To: comp.unix.shell
Date: Wed, 9 Feb 2005 01:05:40 +0100
Organization: T-Online
Lines: 6
Message-ID: <cubk4k$i1h$01$1@news.t-online.com>
Mime-Version: 1.0
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: 8bit
X-Trace: news.t-online.com 1107907540 01 18481 EiZQrzdvpxtogLh 050209 00:05:40
X-Complaints-To: usenet-abuse@t-online.de
X-ID: XHUFRiZfwemeu8lvXqFVVssQ7+85Cma1K0XeG8h3F5eRwYyntVXHoc
Xref: news.earthlink.net comp.os.linux.misc:636310 comp.unix.shell:166347
comp.unix.questions:123232
X-Received-Date: Tue, 08 Feb 2005 16:07:12 PST
(newsspool2.news.pas.earthlink.net)



Is this a redirection of ALL (?) output of ALL (?) statements to the file
myfile.dat?

Wouldn't it be better to use tee instead?

Peter

</quote>


Both aliases killfiled.



AC
Back to top
Chris F.A. Johnson
*nix forums Guru


Joined: 20 Feb 2005
Posts: 2268

PostPosted: Sat Feb 19, 2005 8:46 pm    Post subject: Re: [HS] Re: wildcard's in scripts Reply with quote

On Thu, 03 Feb 2005 at 09:19 GMT, Stephane CHAZELAS wrote:
Quote:
2005-02-2, 23:58(+00), Chris F.A. Johnson:
On Wed, 02 Feb 2005 at 18:23 GMT, new2linux wrote:
Chris, which kind of quotes ? do you have an example ? i've actually
tried quotes, both single & double and it didn't work.

Are you talking to me?

Please include relevant parts of the post so that I know what you
are referring to.
[...]

Chris, as you appear to be using slrn, please note that you can
hist <Meta-p> or <Esc-p> to retrieve the article to which the
current article is replying.

I know that, and I do use it. But it's annoying, and with
intelligent quoting, unnecessary.

--
Chris F.A. Johnson http://cfaj.freeshell.org/shell
===================================================================
My code (if any) in this post is copyright 2005, Chris F.A. Johnson
and may be copied under the terms of the GNU General Public License
Back to top
Heiner Steven
*nix forums Guru Wannabe


Joined: 19 Feb 2005
Posts: 170

PostPosted: Sat Feb 19, 2005 8:46 pm    Post subject: Re: Passing parameters back from a function Reply with quote

Stu wrote:

Quote:
Can somebody show me the best way to pass set parameters back from a
function within a shell script. I know the following code should work
(see below) since parm1 and parm2 are global variables.

setit()
{
parm1="hello"
parm2="world"

}

parm1=""
parm2=""
setit parm1 parm2

At this point I would like to see $parm1="Hello"

Lets assume that setit() is in a file called y.sh and the caller is in
a file x.sh (two different files). I know I have to source in y.sh to
make the function available, and doing this will make the use of
"Global Variables" that much harder to track down that why I want to
pass them as a parmeter list and have the values in the list come back
to the caller set.

A more accurate description using "C" code would be as follows:

void
setit(int parm1)
int *parm1
{
*parm1=44;
return;
}

main()
{
int parm1;
setit(&parm1)
}


Am I worried about nothing ? Secondly, can what I want be done with in
KSH.

You want arguments to be passed by reference. This is not directly
possible in ksh. You can however use call-by-nmae, which lets
you pass the *names* of the variables that should get the return
code. Barry already pointed out that "eval" is needed in this
case. This kind of parameter passing is that useful, that
ksh93 even invented a new syntax for it (typeset -n, see Janis'
posting).

But often you don't need either of them. Functions often are used
in exactly the same way as external commands are, and if
you want to get and process the results of them, you usually use
command substitution, or directly use the output of the
function e.g. in a pipe:

add() { expr "$1" \+ "$2"; } # write result to standard output

result=`add 21 21`

or

add 21 21 | awk '{print "the result is", $0}'

Heiner
--
___ _
/ __| |_ _____ _____ _ _ Heiner STEVEN <heiner.steven@nexgo.de>
\__ \ _/ -_) V / -_) ' \ Shell Script Programmers: visit
|___/\__\___|\_/\___|_||_| http://www.shelldorado.com/
Back to top
Marty
*nix forums Guru


Joined: 16 Mar 2005
Posts: 660

PostPosted: Sat Feb 19, 2005 8:46 pm    Post subject: [HS] Re: wildcard's in scripts Reply with quote

2005-02-2, 23:58(+00), Chris F.A. Johnson:
Quote:
On Wed, 02 Feb 2005 at 18:23 GMT, new2linux wrote:
Chris, which kind of quotes ? do you have an example ? i've actually
tried quotes, both single & double and it didn't work.

Are you talking to me?

Please include relevant parts of the post so that I know what you
are referring to.
[...]


Chris, as you appear to be using slrn, please note that you can
hist <Meta-p> or <Esc-p> to retrieve the article to which the
current article is replying.

--
Stéphane
Back to top
Frank Dietrich
*nix forums beginner


Joined: 19 Feb 2005
Posts: 22

PostPosted: Sat Feb 19, 2005 8:46 pm    Post subject: Re: adding leading zeros to a filename Reply with quote

rupert schrieb:
Quote:
I've got a directory of photos called:

1.jpg
.....
10.jpg
....
100.jpg

and I can't for the life of me work out how to write a script to add
leading zeros to the filenames so they are in the form

001.jpg
.....
010.jpg
....
100.jpg

If you need it for one time only, you can try this

---------------------------
#!/bin/sh

for file in ?.jpg
do
mv $file '00'$file
done

for file in ??.jpg
do
mv $file '0'$file
done
---------------------------

Frank
Back to top
Janis Papanagnou
*nix forums Guru


Joined: 24 Feb 2005
Posts: 450

PostPosted: Sat Feb 19, 2005 8:46 pm    Post subject: Re: Passing parameters back from a function Reply with quote

Stu wrote:
Quote:
Barry Margolin wrote:

In article <1108697901.614706.212320@f14g2000cwb.googlegroups.com>,
"Stu" <beefstu350@hotmail.com> wrote:


Can somebody show me the best way to pass set parameters back from

a

function within a shell script. I know the following code should

work

(see below) since parm1 and parm2 are global variables.

setit()
{
parm1="hello"
parm2="world"

}

parm1=""
parm2=""
setit parm1 parm2

At this point I would like to see $parm1="Hello"

setit ()
{
eval \$$1='"hello"'
eval \$$2='"world"'
}

--
Barry Margolin, barmar@alum.mit.edu
Arlington, MA
*** PLEASE post questions in newsgroups, not directly to me ***



I am not to sure I understand amd I missing something. Can you please
explain. Thanks

cat x.sh
#!/bin/ksh

setit()
{
eval \$$1='"hello"'
eval \$$2='"world"'

Barry meant:

eval $1='"hello"'
eval $2='"world"'

Quote:
}

setit parm1 parm2

./x.sh
./x.sh[2]: =hello: not found
./x.sh[3]: =world: not found


Janis
Back to top
Marty
*nix forums Guru


Joined: 16 Mar 2005
Posts: 660

PostPosted: Sat Feb 19, 2005 9:00 pm    Post subject: Re: Announcing the friendly interactive shell Reply with quote

2005-02-16, 04:43(+00), Faux_Pseudo:
Quote:
_.-In comp.unix.shell, liljencrantz@gmail.com wrote the following -._
Oh, I agree 100%. The notifications in fish are just like the ones bash
emits when you press enter, only they are printed whenever the job
ends, instead of waiting for you to press enter. After a notification
event is printed, the commandline is repainted, so you are never ever
interrupted, and the commandline always diplays what you are doing. Try
the command 'sleep 5', and compare the behaviour of fish with that of
bash.

Ok now that that is better explained I like it. I would request one
improvement though. Once in a while I do something like
$ foo.sh &
and forget it is there until I go back and check on it after a while
and wonder why it hasn't finished. It would be better if the script
or interactive command was waiting for input if the shell let me know
even if I have redirected all output to /dev/null. Also if when I
typed jobs (which is a built in in bash) if it let me know what the
cpu usage of the backgrounded command was (or given the nanosecond
gaps of cpu usage in a process an average of the last second or so
would be nice) so that if it was 00% and I know it should be much
higher than that I know I should be debugging it.
[...]


With zsh 4.2.x, on Linux you can do (put in ~/.zshrc for
instance):

# BEGIN
typeset -F SECONDS # floating point SECONDS
typeset -A cpu_times # recorded cpu times
typeset -F last_status_time
zmodload -i zsh/parameter
autoload -U colors
colors
[[ $functions[precmd] = *output-job-status* ]] ||
functions[precmd]+='
: output-job-status
emulate -L zsh
if (( $#jobstates )); then
local -a p
local i j s t st
local -F u
print -rn -- $fg_no_bold[blue]
s=$SECONDS
for j in ${(k)jobstates}; do
IFS=: eval "p=(\${=jobstates[\$j]})"
printf >&2 "%1s%%%-2d%50s[%c]:" "$p[2]" $j "${jobtexts[$j]}" ${(U)p[1]}
for i in $p[3,-1]; do
pid=${i%%\=*}
if IFS=" " read -rA st < /proc/$pid/stat; then
(( t = ${(j,+,)st[14,17]} ))
(( u = (t - cpu_times[$pid]) / (s - last_status_time)))
(( u >= bold_cpu_threshold )) && print -rn -- $fg_bold[red]
printf " %5d[%c]%2.1f%%" $pid ${(U)i#*=} $u
(( u >= bold_cpu_threshold )) && print -rn -- $fg_no_bold[blue]
cpu_times[$pid]=$t
fi
done
print
done
last_status_time=$s
print -rn $reset_color
fi
'
bold_cpu_threshold=10 # display in bold cpu usage above 10%
# END

it will display the status of the background tasks above the
prompt in blue (on terminals supporting ANSI colors) with the
percentage of cpu usage for every process between two prompt
displays (in bold red if above 10%).

--
Stéphane
Back to top
Icarus Sparry
*nix forums Guru


Joined: 19 Feb 2005
Posts: 342

PostPosted: Sat Feb 19, 2005 9:00 pm    Post subject: Re: Korn Shell: Using sed to replace string with multiline string? Reply with quote

On Sat, 19 Feb 2005 12:07:10 -0800, jchauvin wrote:

Quote:

Chris F.A. Johnson wrote:

sed '/|-insert_data_here-/{r filename; d;}'



Still does not work at least on a SGI running IRIX 6.4. The error
message is:

Too many {'s

Try

sed -e '/.../{' -e 'r filename' -e 'd' -e '}'

This works on Solaris 8, which gives the same error message as your SGI
Back to top
Martijn Lievaart
*nix forums addict


Joined: 19 Feb 2005
Posts: 60

PostPosted: Sat Feb 19, 2005 9:06 pm    Post subject: Re: SSH/SFTP Connection Forwarding Reply with quote

On Sat, 19 Feb 2005 11:00:07 -0800, intercom5 wrote:

Quote:
I was wondering if anyone knew how to setup sftp connection forwarding.
What I mean by this is that a user tries to connect via sftp to a
remote server, say login.domain.com. I want this server (the login
server) to then redirect the client to another server based on which
client it is.

For example, user1's files are on server1.domain.com and user2's files
are on server2.domain.com. But if either of them connects to
login.domain.com, they will be forwared to their correct server
(server1 for user1 and server2 for user2).

I know something like this is possible, because my university did it -
I just have no idea where to start.

Easy if you control the firewall (or install one on that machine). Just
redirect the connection to the appropriate machine based on the source
address. Any decent firewall should be able to do that.

M4
--
Ah, the beauty of OSS. Hundreds of volunteers worldwide volunteering
their time inventing and implementing new, exciting ways for software
to suck. -- Toni Lassila in the Monastry
Back to top
Marty
*nix forums Guru


Joined: 16 Mar 2005
Posts: 660

PostPosted: Sat Feb 19, 2005 9:07 pm    Post subject: Re: Announcing the friendly interactive shell Reply with quote

2005-02-15, 14:21(-0Cool, bsh:
Quote:
Chris F.A. Johnson wrote:
On Tue, 15 Feb 2005 at 10:35 GMT, Axel Liljencrantz wrote:
...

This is 2005, and writing 'foo = bar' doesn't work? And how
intuitive is it that an environment variable with spaces is
separated into multiple arguments unless it is quoted?
Changing it could break many scripts.

No!

Because of a little-used construct called a "variable
assignment list" that is possible in k/sh, one _cannot_
have entrained semicolon(s) because of its original purpose
to define per-process environment variables. That is:

var1=a var2=b var3= # no semicolons nec in a v.a.l. !
var1=a; var2=b; var3= # most people do this
# define additional env vars as v.a.l. before /path/app
var1=a var2=b var3= /path/app options...

Obviously, any semicolon would disallow the v.a.l. from
being semantically "attached" to the /path/app invocation,
and "floating" equal-signs would make the parsing ambiguous.

The kludge of mandating spaces in csh either around _both_
sides of the equal sign or none at all, is a terrible idea.
The c-shell-ism of optional whitespace around the equal
sign always was syntactically problematic, if you ask me....
[...]


rc has no problem with

; a = 1 b = 2 c = '' env | grep '^[abc]='
a=1
b=2
c=

--
Stéphane
Back to top
Icarus Sparry
*nix forums Guru


Joined: 19 Feb 2005
Posts: 342

PostPosted: Sat Feb 19, 2005 9:16 pm    Post subject: Re: SSH/SFTP Connection Forwarding Reply with quote

On Sat, 19 Feb 2005 11:00:07 -0800, intercom5 wrote:

Quote:
I was wondering if anyone knew how to setup sftp connection forwarding.
What I mean by this is that a user tries to connect via sftp to a
remote server, say login.domain.com. I want this server (the login
server) to then redirect the client to another server based on which
client it is.

For example, user1's files are on server1.domain.com and user2's files
are on server2.domain.com. But if either of them connects to
login.domain.com, they will be forwared to their correct server
(server1 for user1 and server2 for user2).

I know something like this is possible, because my university did it -
I just have no idea where to start.

The obvious first question is why don't server1 and server2 export their
files to login.domain.com? This, together with a suitable password file on
login.domain.com will make it all work without having to hack anything.

If you don't want to do this, then you have to write some code. When you
fire up 'sftp' it starts up a 'ssh user@hostname sftp-server'. You would
somehow have to make firstly the 'login' machine accept the ssh connection,
then make a program (maybe just a shell script) called 'sftp-server' that
decided which machine to connect to, and then made the connection. It would
need to invoke the original sftp-server on the remote end, and copy stuff
between standard input and the remote machine.

Programs like 'nc' 'netcat', 'netpipe' or 'mconnect' may help.

This is a lot more work than just exporting the files from the servers
in the first place.
Back to top
Martijn Lievaart
*nix forums addict


Joined: 19 Feb 2005
Posts: 60

PostPosted: Sat Feb 19, 2005 9:18 pm    Post subject: Re: using ls and sending the output to a file in a certain format. Reply with quote

On Fri, 18 Feb 2005 06:01:59 -0800, trololo wrote:

Quote:
Hi can anyone tell me what command can I execute that does an #ls in a
directory and puts all of the output into a file putting a comma for
every file so that the output should look something like a,b,c,d,e

If ls -m is not what you want:
$ perl -e 'print join(",", <*>), "\n"' >/tmp/file

if you want only files, not directories:
$ perl -e 'print join(",", grep -f, <*>), "\n"' >/tmp/file

(Yes, you guessed it. If I cannot think up a shell solution within three
seconds, I always do it in Perl. Case of hammers and looking like nails I
guess.)

HTH,
M4

--
Ah, the beauty of OSS. Hundreds of volunteers worldwide volunteering
their time inventing and implementing new, exciting ways for software
to suck. -- Toni Lassila in the Monastry
Back to top
Marty
*nix forums Guru


Joined: 16 Mar 2005
Posts: 660

PostPosted: Sat Feb 19, 2005 9:37 pm    Post subject: Re: Announcing the friendly interactive shell Reply with quote

2005-02-16, 04:29(+00), Faux_Pseudo:
[...]
Quote:
* A syntax that doesn't suck. OK, so a shell for scripting should
probably be POSIX compliant, but a interactive shell should focus on
beeing actually useable. This is 2005, and writing 'foo = bar' doesn't
work? And how intuitive is it that an environment variable with spaces
is separated into multiple arguments unless it is quoted?

This would break lots of scripts.

But that would fix many more of them. Most people forget to
quote variables when it is necessary.
And I want the behaviour as it is

Quote:
because to me it is intuative. What you are asking for is easy to
accomplish with things like this:
while read line ; do foo "$line" done < file

I guess you meant:

while IFS= read -r line; do foo -- "$line"; done ;)

Quote:
Otherwise we would have to write a seperate function to split lines up
when it is needless.

Or simply as in zsh: $=foo (or ${=foo}) instead of $foo.

[...]
Quote:
Sometimes I want that and sometimes I don't. I tend to juggle
screen's, X's and the shells copy buffer. While sometimes I think it
would be nice to highlight something in X and then ^Y it in the shell
there are too many times when I know that would be a bad idea.

With zsh, you can put the X cut buffer into the zsh cutbuffer
with:

get-X-cut-buffer() {
killring=("$CUTBUFFER" "${(@)killring[1,-2]}")
CUTBUFFER=$(awk "BEGIN{$(xprop -root -notype CUT_BUFFER0)
print CUT_BUFFER0}")
}
zle -N get-X-cut-buffer
bindkey '^[[2;5~' get-X-cut-buffer

^[[2;5~ is the character sequence sent upon pressing
<Ctrl-Insert> in my xterm.

(<Ctrl-Y> to yank (paste) the cutbuffer in zsh emacs mode)

or again, you can use zsh mouse support (not related to X
selection) at http://stchaz.free.fr/mouse.zsh

--
Stéphane
Back to top
Google

Back to top
Display posts from previous:   
Post new topic   Reply to topic Page 3 of 43 [637 Posts] Goto page:  Previous  1, 2, 3, 4, 5, ..., 41, 42, 43 Next
View previous topic :: View next topic
The time now is Tue Dec 02, 2008 6:36 am | All times are GMT
navigation Forum index » Programming » shell
Jump to:  

Similar Topics
Topic Author Forum Replies Last Post
No new posts Function Pointer Sikandar C 3 Fri Jul 21, 2006 1:23 pm
No new posts Shortening URLs passing through a squid hierarchy Irvine, Doug - Resources Squid 0 Fri Jul 21, 2006 10:15 am
No new posts Arbitrary function with parameter darknails@gmail.com C++ 2 Fri Jul 21, 2006 9:58 am
No new posts mod_rewrite to go from http to https and back sevans@bigskypenguin.com Apache 0 Fri Jul 21, 2006 5:12 am
No new posts Is there C/C++ corresponding function in Linux for Java's... xiebopublic@gmail.com apps 4 Fri Jul 21, 2006 3:22 am

Mortgage Calculator | Bikini Model | Mortgage | Mortgages | Mortgage Calculator
Copyright © 2004-2005 DeniX Solutions SRL
 
Other DeniX Solutions sites: Unix/Linux blog |  electronics forum |  medicine forum |  science forum | 
Privacy Policy


Powered by phpBB © 2001, 2005 phpBB Group
[ Time: 0.2669s ][ Queries: 16 (0.1083s) ][ GZIP on - Debug on ]