0% found this document useful (0 votes)
9 views2 pages

Shell Scripts for Basic Calculations

The document contains several shell script examples for basic arithmetic operations, finding the greatest of three numbers, a menu-driven program for system tasks, and calculating the factorial of a number. Each script prompts the user for input and performs the specified operations, displaying the results accordingly. These examples illustrate fundamental scripting techniques in a Unix-like environment.

Uploaded by

wgfbwivbzlmktlz
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views2 pages

Shell Scripts for Basic Calculations

The document contains several shell script examples for basic arithmetic operations, finding the greatest of three numbers, a menu-driven program for system tasks, and calculating the factorial of a number. Each script prompts the user for input and performs the specified operations, displaying the results accordingly. These examples illustrate fundamental scripting techniques in a Unix-like environment.

Uploaded by

wgfbwivbzlmktlz
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Shell scripts

1)

echo enter two numbers

read a b

echo "Addition: $(($a + $b))"

echo "Subtraction: $(($a - $b))"

echo "AMultiplication: $(($a * $b))"

echo "Quotient: $(($a / $b))"

echo "Remainder: $(($a % $b))"

or

echo enter two numbers

read a b

s=`expr $a + $b`

echo sum=$s

s=`expr $a - $b`

echo Difference =$s

s=`expr $a \* $b`

echo Product =$s

s=`expr $a / $b`

echo quotient =$s

s=`expr $a % $b`

echo Remainder =$s

2) Greatest of three numbers

echo Enter three numbers

read a b c

if [ $a -gt $b -a $a -gt $c ]

then

echo $a
elif [ $b -gt $c -a $b -gt $a ]

then

echo $b

else

echo $c

fi

3) Menu driven program

echo -e "MENU\n 1. List of files\n 2. Processes of User\n 3. Today's Date \n4. Users of system\n 5. quit"

echo " Enter your option "

read choice

case "$choice" in

1) ls -l ;;

2) ps -f ;;

3) date ;;

4) who ;;

5) exit ;;

*) echo "Invalid option"

esac

4) Factorial

echo "Enter a number"

read n

f=1

while [ $n -ne 0 ]

do

f=$(($f * $n))

n=$(($n -1))

done

echo "Factorial ="$f

Common questions

Powered by AI

A shell script can determine the greatest of three numbers by using conditional statements to compare the numbers. The steps involve reading the three numbers, say a, b, and c. Then, use if-elif-else structure to compare the numbers: First, check if 'a' is greater than both 'b' and 'c'. If true, 'a' is the greatest. If not, check if 'b' is greater than both 'c' and 'a'. If true, 'b' is the greatest. Otherwise, 'c' is the greatest. This approach ensures that all possible conditions are evaluated, determining the largest number accurately .

Designing the user interaction flow in a shell script demands careful analysis of user needs and usability principles. Key considerations include providing clear instructions and feedback, ensuring options are intuitively understandable, and correcting user paths through informative error messages. Scripts should optimize the flow where users make expected actions smoothly, such as repeating a menu after an action or confirming critical tasks like exits. Minimizing input steps without sacrificing functionality ensures more efficient operation. Designing with accessible command shortcuts and structured choice layouts enhances the user experience, making it an integral part of sophisticated shell scripting design .

Integer arithmetic in a shell script can be performed using arithmetic expansion and external commands like 'expr'. Arithmetic expansion uses the syntax '$(($a + $b))' for operations such as addition, subtraction, multiplication, division, and modulus. This method is compact and easy to use within the script. Alternatively, the 'expr' command can be employed, especially in older shell environments, using backticks and escaping operators such as multiplication. This method allows expressions like 's=`expr $a + $b`' for addition, handling integer arithmetic via external evaluation in scripts .

Computing a factorial in a shell script involves using a loop to iterate through numbers decrementing from n to 1. The process begins by initializing a factorial accumulator variable, typically set to 1. The shell script reads the input number 'n' and then enters a while loop. The loop condition checks that 'n' is not equal to zero. Inside the loop, the factorial accumulator 'f' is updated by multiplying it with 'n', and then 'n' is decremented by 1. This iterates until 'n' reaches zero, at which point the loop terminates, and the factorial result is printed. This approach utilizes the straightforward iterative method to compute factorials in a shell environment effectively .

Shell scripts handle user inputs primarily using the 'read' command, which captures user-entered data during execution. Ensuring robust input validation involves applying defensive coding practices, such as checking if the inputs meet expected criteria (e.g., numerical data, non-empty strings). Conditional statements can validate input ranges, types, and expected formats. For instance, before using inputs in arithmetic operations, verify they are indeed numbers. When expecting choices in menu-driven scripts, the script can loop to prompt re-entry until valid inputs are received. These strategies protect against incorrect or malicious inputs, maintaining script integrity and intended functionality .

A menu-driven shell script serves to present users with a list of options to choose from, each performing a specific operation. Essential functions involve presenting a menu using echo statements and a 'case' structure to handle user inputs for selected options. The script implementation begins with displaying a menu of choices, such as viewing file lists, checking user processes, or showing today's date. The user input is read and processed using a 'case' statement, which executes specific commands such as 'ls -l', 'ps -f', or 'date' depending on the choice made. The script loops or exits based on the user's decisions, ensuring ease of interaction and functionality encapsulation .

Using 'expr' for arithmetic operations in shell scripting presents several disadvantages compared to modern alternatives like '$(())'. 'Expr' requires external processes and uses backticks or complex syntax for simple arithmetic tasks, which is less efficient. This method necessitates escape characters for operators like asterisk (*) and may cause readability and maintenance challenges. Additionally, arithmetic expansion provides a more integrated, cleaner syntax with fewer opportunities for syntactical errors, supports more complex expressions internally within the shell, and executes faster by avoiding the overhead of spawning external processes .

The 'case' statement in a shell script serves to simplify decision-making by matching patterns instead of evaluating pure conditions, which is more efficient for handling multiple-choice inputs. It is particularly useful for menu-driven applications where different user options lead to various actions. Compared to 'if-else' statements, 'case' improves readability and manageability, especially with many alternatives, by cleanly separating cases beneath a single code block. Each pattern followed by commands supersedes the need for extensive condition checks, making it faster and less error-prone when expanding future cases, providing better maintenance and logical control .

When implementing a division operation in a shell script, the logical structure must handle various edge cases to avoid errors or undesirable behavior. Primarily, checking if the divisor is zero is crucial, as division by zero is undefined and will cause execution errors. The script can include a conditional to detect a zero divisor early and output an error message or handle it appropriately. The division is performed using '$((a / b))' or 'expr', ensuring integer division is correctly applied in shell scripts, which do not naturally handle fractional results. Handling input validity and type checking can further ensure reliable division operations in diverse use cases .

In shell scripting, controlling mathematical operation precedence and correct expression evaluation involves using arithmetic expansion syntax and understanding operator precedence rules. Arithmetic expansion with '$(())' respects traditional mathematical precedences, allowing nested expressions like '$(($a + ($b * $c)))' to evaluate correctly. It's crucial to use parentheses to override default precedences where necessary, ensuring that operations yield expected results. Additionally, testing expressions comprehensively during script development prevents unforeseen precedence-related bugs, reinforcing accurate script functionality .

You might also like