Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Accepts 2 Nos at Command Line

Status
Not open for further replies.

Cap2010

Programmer
Mar 29, 2000
196
CA
Hi again,<br><br>I am learning Linux and wanted to know<br>how make a shell script where by using a parameter<br>to accept 2 nos at one command line and thereafter<br>calculate either to add, subtract and return the output<br>of addition and subtraction.<br><br>e.g. command 1 + 2<br>where by command 1 is add with 2<br><br>command 1 - 2&nbsp;&nbsp;&nbsp;- here using the same above command<br>subtraction takes place.<br><br>Need your help?<br>Thanks<br><br><br>
 
OK, this might turn out to be a little trickier than you expected, but I'll try and mke it easy for you :)<br><br>Your examples actually pass 3 parameters to the program - &quot;1&quot;, &quot;+&quot;, and &quot;2&quot; for example.<br><br>The following shell script will work using the named parameters:<br><FONT FACE=monospace><br>#!/usr/bin/sh<br><br>expr $1 $2 $3<br></font><br>But what if you want to do, for example, &quot;1 + 2 - 3&quot;.&nbsp;&nbsp;The previous shell script fails because it won't &quot;see&quot; the &quot;-&quot; and &quot;3&quot; at the end.&nbsp;&nbsp;A small change will make it work OK:<br><FONT FACE=monospace><br>#!/usr/bin/sh<br><br>expr $*<br></font><br><br>See the man page for <FONT FACE=monospace>expr</font> for more details on how it works(<FONT FACE=monospace>man expr</font>, and look at the <FONT FACE=monospace>sh<FONT FACE=monospace> (or <FONT FACE=monospace>bash</font>) man page for more details on positional parameters.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top