User Tools

Site Tools


cs:bash_language:example_3
Return to Home page

Example 3

Concepts:
Command line arguments in bash.

Text:
Implement a bash shell script that prints the result of the sum of a set of numbers passed to the script as a command line argument.

A number of equivalent solutions have been proposed. The differences between them consists on the way used to iterate between program arguments.

Example:
Running the script as follow:

$ ./bash_ex3.sh 2 3 4 5 6

the provided output is:

1) Arguments: 2 3 4 5 6  Sum: 20
2) Arguments: 2 3 4 5 6  Sum: 20
3) Arguments: 2 3 4 5 6  Sum: 20

Solution:

bash_ex3.sh
# Implement a bash shell script that prints the result of the sum of a set
# of numbers passed to the script as a command line argument.
# A number of equivalent solutions have been proposed. The differences between
# them consists on the way used to iterate between program arguments.
#    Example:
# $ ./bash_ex3.sh 2 3 4 5 6
# 1) Arguments: 2 3 4 5 6  Sum: 20
# 2) Arguments: 2 3 4 5 6  Sum: 20
# 3) Arguments: 2 3 4 5 6  Sum: 20
 
 
#!/bin/bash
 
 
# First solution
final_sum=0
 
echo -n "1) Arguments: "
# The variable $* contains all the program arguments with the exclusion of 
# the program name
for a in $*
do
   echo -n "$a "
   final_sum=$[$final_sum+$a]      
done  
echo " Sum: $final_sum"
 
 
# Second solution
final_sum=0
 
echo -n "2) Arguments: "
# echo writes content of the variable $* to the screen
# The symbols ` ` represents the output of the command
for a in `echo $*`
do
   echo -n "$a "
   final_sum=$[$final_sum+$a]      
done  
echo " Sum: $final_sum"
 
 
# Third solution
final_sum=0
 
echo -n "3) Arguments: "
# The code $(command) corresponds to `command`
for a in $(echo $*)   
do
   echo -n "$a "
   final_sum=$[$final_sum+$a]      
done  
echo " Sum: $final_sum"

If you found any error, or if you want to partecipate to the editing of this wiki, please contact: admin [at] skenz.it

You can reuse, distribute or modify the content of this page, but you must cite in any document (or webpage) this url: https://www.skenz.it/cs/bash_language/example_3
/web/htdocs/www.skenz.it/home/data/pages/cs/bash_language/example_3.txt · Last modified: 2019/02/26 14:35 (external edit)

Privacy Policy