Created by Storming Robots
Elizabeth | STORMING ROBOTS Page 1 of 24
Using the Windows Linux Subsystem
last update: June 10th, 2020
Table of Contents
Installing the Windows Linux Subsystem................................................................................................................ 3
Potential issues on conflicts in C/C++ installation: ......................................................................................... 8
Install a programming editor .............................................................................................................................. 9
Compiling and linking without using an IDE ........................................................................................................ 10
Sample codes ................................................................................................................................................ 10
how to build (compile + link + execute) ............................................................................................................ 10
The three most basic compiler options you should know: ........................................................................... 11
Basic linux commands you should know .............................................................................................................. 13
Linux Commands Exercises ................................................................................................................................... 18
Part I ................................................................................................................................................................. 18
Simple standard output ............................................................................................................................. 18
File paths and folder navigation ............................................................................................................... 18
Permissions ................................................................................................................................................. 19
Process Information ................................................................................................................................... 19
Searching..................................................................................................................................................... 19
Part II ................................................................................................................................................................ 20
Sample Scripting ................................................................................................................................................... 21
Show how to do factorial of a number using “while” .................................................................................. 21
Show how to do factorial of a number using “for” ....................................................................................... 21
Automate a test with usaco’s #.in test files .................................................................................................. 21
Read one line at a time from a file. .............................................................................................................. 21
Function Script Samples ............................................................................................................................... 23
Created by Storming Robots
Elizabeth | STORMING ROBOTS Page 2 of 24
Created by Storming Robots
Elizabeth | STORMING ROBOTS Page 3 of 24
Installing the Windows Linux Subsystem
1. Run the PowerShell as an Administrator
a. Type in powershell in the Search window
b. Right mouse click Windows PowerShell and click “Run as administrator”
2. In the PowerShell window type the command:
Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux
Created by Storming Robots
Elizabeth | STORMING ROBOTS Page 4 of 24
You will then see this…
3. Reboot your machine
4. Install Linux
a. Run Microsoft Store
b. Type linux in the search window
c. Select Ubuntu
d. Click Install
e. When finished click Launch
f. You will need to wait a few minutes as the installation completes
Here are some screenshots:
Created by Storming Robots
Elizabeth | STORMING ROBOTS Page 5 of 24
5. Create user
a. You will be prompted for a username and password
b. Don’t forget your password
Sample user name … DO NOT Use the same one… this is just a sample.
Created by Storming Robots
Elizabeth | STORMING ROBOTS Page 6 of 24
6. Update Linux
a. Type sudo apt update && sudo apt upgrade (or sudo apt-get …)
b. When prompted to continue, hit Y and enter.
You will see a lot of status display like this:
7. Install Compilers
a. Type sudo apt install gcc
b. When prompted to continue, hit Y and enter.
c. Type “ sudo apt install g++”
d. When prompted to continue, hit Y and enter.
$ sudo apt install gcc
$ sudo apt install g++
Created by Storming Robots
Elizabeth | STORMING ROBOTS Page 7 of 24
8. Test compiler installation
a. Use the default editor “nano” to create a sample code, such as: main.cpp. At complete
b. Test it out with some simple sample code, such as this:
c. Hit ctrl-x to save and exit
d. Now type: g++ -lm -std=c++0x main.cpp -o main
e. It should have compiled ok. If so type in: ./main
9. You should be set up properly.
$ nano main.cpp
1. #include <iostream> 2. using namespace std; 3. 4. int main ( ) 5. { 6. int i; 7. cout << "Please enter an integer
value: ";
8. cin >> i; 9. cout << "The value you entered
is " << i;
10. cout << " and its double is
" << i*2 << ".\n";
11. return 0;
12. }
Created by Storming Robots
Elizabeth | STORMING ROBOTS Page 8 of 24
POTENTIAL ISSUES ON CONFLICTS IN C/C++ INSTALLATION:
Conflict in the g++ installation :
You need to rebuild the dependency :
If this still does not resolve the conflict, you may need to reinstall the following packets. However, do it one at
a time, and watch for messages…
There may be time when it told you to do the following, do it as instructed:
$ sudo apt-get install libgmpv4-dev
$ sudo apt-get install g++
sudo apt-get install gcc-5-multilib
sudo apt-get install lib32gcc1
sudo apt-get install libx32gcc1
sudo apt-get install gcc-5
sudo apt-get install libx32gcc-5-dev
$ sudo apt autoremove
Created by Storming Robots
Elizabeth | STORMING ROBOTS Page 9 of 24
INSTALL A PROGRAMMING EDITOR
There are quite a few programming editors available. Here lists 3 commonly used ones. To install : “sudo apt-
get update” before installing another package
1) Nano
⎯ Light weight text editor, but the most primitive one. Just run it from the shell command
window.
⎯ Pretty easy to navigate, nothing fancy though. No plug-ins features, but may utilize its
configuration file to customize somewhat.
⎯ Should come pre-installed.
2) Kate
⎯ This is a hefty graphical editor. Will need to run a graphical terminal windows in order to run
this. Cannot run this in the simple command shell window.
⎯ Some find it much more intuitive to navigate. Some plug-ins.
⎯ Need to install yourself : “ sudo apt-get install kate “
3) VIM
⎯ This is a light weight editor. Can run this in the simple command shell window.
⎯ Some find it difficult to navigate. Many plug-ins available, more flexible than Kate. Based on
SLANT community , Vim is ranked 1st. It is a lighter weight and fast editor.
⎯ Mostly come pre-installed, but you may need to install the plugins for some advanced features.
“…Vim is a powerful, portable, keyboard based text editor. Being text-based, vim is lightning fast,
with an incredible set of features developed over its multi decade existence….” By SLANT.
I highly recommend to learn how to use VI.
Reference this packet to have a crash course using VI.
Concise lookup sheet:
- https://www.cheatography.com/typo209/cheat-sheets/comprehensive-vim-cheat-sheet/pdf
- http://www.nathael.org/Data/vi-vim-cheat-sheet.svg
Interactive vi Editor Tutorial: Here you can practice Vim with context-aware help menu
You may want to customize color right at the beginning. Here is how:
➢ Look up available default color scheme from /usr/share/vim/vim74/colors/
➢ Edit .vimrc
➢ E.g. to add murphy scheme, add “color murphy” into the .vimrc
Created by Storming Robots
Elizabeth | STORMING ROBOTS Page 10 of 24
Compiling and linking without using an IDE
SAMPLE CODES
HOW TO BUILD (COMPILE + LINK + EXECUTE)
1) How to build (Compile and link) a single executable out of several files
13. //main.cpp --------------------
---------
14. #include <stdio.h>
15. #include <myH1.h>
16. #include <myH2.h>
17.
18. int main ()
19. {
20. ... write the code to test
the functions..
21. e.g.
22. cout << "Enter number
to find fib: ";
23. cin >> num;
24. cout << fib(num) <<
endl;
25. }
26. // <myH1.h>
27.
28. int fact (int i);
29. int fib (int);
30.
31. // <myH2.h>
32.
33. int gcd (int, int);
34.
35. // myFuncs2.cpp -----
--------
36. #include <iostream>
37. using namespace std;
38. #include <stdio.h>
39. #include <myH2.h>
40.
41. int gcd(int a, int b)
42. {
43. …
44. }
45. //myFuncs1.cpp ------
-------
46. #include <iostream>
47. using namespace std;
48. #include <stdio.h>
49. #include <stdlib.h>
50. #include <string.h>
51. #include <myH1.h>
52.
53. int fact(int i)
54. {
55. …
56. }
57.
58. int fib(int order) {
59. …
60. }
Created by Storming Robots
Elizabeth | STORMING ROBOTS Page 11 of 24
2) How to build a static library file (*.a) out of several files (no main() ) , then link the static library *.a
file(s) with your main file (the one with main() ) .
3) How to build a shared library file (*.so) out of several files (no main() ) , then link the shared library
*.so file(s) with your main file (the one with main() ) .
THE THREE MOST BASIC COMPILER OPTIONS YOU SHOULD KNOW :
-I: (upper case i) include path for header files -l : (lower case of ‘L’) -L : Library path -D : Preprocessor macro
Compile and link a single executable out of several files. Note the main.cpp is the only file containing the
function main()
1. g++ -Wall main.cpp myFuncs1.cpp myFuncs2.cpp -I./ -o runThis 2.
Build a static library file (*.a) out of several files (no main() ) , then link the static library *.a file(s) with your
main file (the one with main() ) .
3. g++ -Wall -c myFuncs1.cpp myFuncs2.cpp -I./ 4. ar -cvq libSample.a myFuncs1.o myFuncs2.c 5. ar -t libSample.a 6. g++ -Wall main.cpp -L./ -lSample -I./ -o runThis2 7.
How to build a shared library file (*.so) out of several files (no main() ) , then link the shared library *.so file(s)
with your main file (the one with main() ) .
Do note : “-I” (this lower case of ‘L’) .
8. g++ -Wall -c -fPIC myFuncs1.cpp myFuncs2.cpp -I./ 9. g++ -shared -o libmySample.so myFuncs1.o myFuncs2.o 10.
11. g++ -Wall main.cpp -L./ -lmySample -I./ -o runThis3
12.
Note that the “-L./” and “-I./” (this lower case of ‘L’) indicates the path where the build will find the library
file and header file respectively.
Created by Storming Robots
Elizabeth | STORMING ROBOTS Page 12 of 24
May use LD_LIBRARY_PATH to add in customize library path, C_INCLUDE_PATH to add in customized include
path.
13.
14. export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:./ # if your *.so file is
in ./
15. export C_INCLUDE_PATH=$C_INCLUDE_PATH:./ # if your *.h files
are in ./
16.
17. g++ -Wall main.cpp -lmyFuncs -o runThis3 # do not need -L , -I
To demonstrate how the “-D” commonly being used:
18. g++ -Wall main.cpp myFuncs1.cpp myFuncs2.cpp -I./ -o runThis -D_SR_
19.
20. ./runThis
21.
Try this, and observe the difference from build it without -D_SR_
Reference (for windows OS instead):
⎯ Setting the Path and Environment Variables for Command-Line Builds ⎯ Walkthrough: Compiling a C Program on the Command Line
Created by Storming Robots
Elizabeth | STORMING ROBOTS Page 13 of 24
Basic linux commands you should know
Here is a very small set of commands that you should know. Try them out and observe what it does.
To look up full description of a command, use “man”, e.g. man ls
To look up a concise one-line manual page descriptions, use “whatis”, e.g. whatis ls
The ~50s linux commands that you should know as a software developer on Linux platform...
Files/ Folders
cat : concatenate files and print on the standard output
cd : (built-in) change directory or folder.
cmp : compare two files byte by byte
cp : copy files and directories
diff : compare files line by line
dir : list directory contents
ln : make links between files
ls : list directory contents
mkdir : create a directory
more : file perusal filter for crt viewing
mount : mount a filesystem
mv : move (rename) files
rm : remove files or directories
touch : change file timestamps
wc : print newline, word, and byte counts for each file
Search and Regular Expression
find : search for files in a directory hierarchy
grep : print lines matching a pattern
locate : find files by name
sed : stream editor for filtering and transforming text
sort : sort lines of text files
which : locate a command
system command (handle with care)
shutdown (built in) system shutdown
Security
chmod : change permissions of a file
chown : change ownership of a file
pwd : print name of current/working directory
sudo : execute a command as another user
Created by Storming Robots
Elizabeth | STORMING ROBOTS Page 14 of 24
Editing
nano : Nano's ANOther editor, an enhanced free Pico clone
vim : Vi IMproved, a programmers text editor
kate : Advanced text editor for KDE
Console display
clear : clear the terminal screen
echo : display a line of text
head : output the first part of files
more : file perusal filter for crt viewing
tail : output the last part of files
System utilities
alias : (built-in) set up alias for any commands
date : print or set the system date and time
export : export an environment variables and their values to all child (subsequent) processes.
man : an interface to the on-line reference manuals
uname : get name and information about current kernel
whoami : current user
history : GNU History Library
lscpu : display information about the CPU architecture
set : set environment variables
About the disk space
df : report file system disk space usage
du : estimate file space usage
Networking
ifconfig : (built-in) network configuration
ssh : OpenSSH SSH client (remote login program)
traceroute : (built-in) display the network route to a remote node
Package / Download
sudo apt-get : APT package handling utility : : command-line interface
wget : The non-interactive network downloader.
curl : transfer a file from a remote site.
Process info
htop : interactive process viewer
kill : send a signal to a process
ps : report a snapshot of the current processes.
Created by Storming Robots
Elizabeth | STORMING ROBOTS Page 15 of 24
top : display Linux processes
time : run programs and summarize system resource usage
uptime : Tell how long the system has been running.
watch : execute a program periodically, showing output fullscreen
Jobs
bg (built-in) move your process to the background
fg (built-in) move your process to the foreground
Ctrl+Z (built-in) suspend a process
misc
./ from current folder
../ one branch up : parent folder. ../../ == two branches up, etc.
!! Repeat the last command
useless but fun (you ma need to run sudo apt-get to install)
cal : displays a calendar and the date of Easter
banner : print large banner
fortune : print a random, hopefully interesting, adage
Try them out ***(Observe the behavior after each command. Be Inquisitive)
1. ls # l = lower case of L 2. man ls 3. cd / 4. pwd 5. cd ~/; pwd 6. mkdir playDir; pwd 7. cd playDir 8. ls -l # -l = lower case of L
9. ls -la 10. ls -ltra
11. cd ..
12. cd /mnt/c # This is your C Drive. Be curious! Check out the
sub-folders...
13. ls -l
14. ls -ltRa | more # this is LONG! So do “Ctrl-C” at any time to get
out
15. cd ~/; pwd
16. ls -l
17. mv playDir play
18. ls -l
19. echo “This is the 1st line.” > test1.txt
20. echo “This is the 2nd line.” >> test1.txt
21. cat test1.txt
22. echo “This is a hidden file.” > .test2.txt
23. ls -ltra > test1.txt
24. ls -l | wc -l >> test1.txt
Created by Storming Robots
Elizabeth | STORMING ROBOTS Page 16 of 24
25. echo “This is the end \! ” >> test1.txt
26. cat test1.txt
27. grep “this is” test1.txt
28. grep -i “this is” test1.txt
29. cd ~
30. pwd
31. clear
32. ls -lr # -l = lower case of L
33. dir -lr
34. ls -lR
35. dir -lR
36. ls -l | grep "^\.” # list all hidden files and directories
37. ls -l | grep “^d” # list sub-directories
38. ls -ltR | grep “^d”
39. ls -l | wc -l # count of nodes (files, directories, links,
etc.)
40. ls -lR | grep "^d”
41. alias ldir=’ls -lR | grep "^d"’ #you just created a new command!
42. ldir
43. clear
44. date
45. date +%D
46. date +"%T"
47. time
48. man -? > help.txt
49. tail -f help.txt
50. ls /root/
51. sudo ls /root/
52. wget https://www.stormingrobots.com/prod/pdf/csSyllabus.pdf &
53. du
54. du -sh
55. du -h * -d 1
56. du – h * -d 3
57. du -h * | sort -n # show and sort files by disk space usage size
58. du -h * | sort -nr
59. du -a . | sort -nr | head
60. du -a . | sort -nr | tail
61. df
62. df -h
63. df /home
64. echo "echo \"Hello World \" " > test.sh
65. cat test.sh
66. ls -l test.sh # you see: -rw-r--r-: 1 … test.sh
67. ./test.sh # fail to run
68. chmod +x test.sh
69. ls -l test.sh # you see: -rwxr-xr-x 1 … test.sh
70. ./test.sh
71. ps -ef
72. watch -n 1 "ps -ef" &
73. ps # find the PID (process ID) for this watch command
74. kill 3000 # replace 3000 with the PID of the “watch”
process
75. ps # now you see the process is gone
76. clear
77. history
78. !!
& == runs in background
Created by Storming Robots
Elizabeth | STORMING ROBOTS Page 17 of 24
79. !w
Find a number corresponding to one of the previous commands. E.g. one of them is 50:
80. !50 # if 50 exists in your history commands list
81. top
82. Ctrl+Z # this suspend the process “top”
83. jobs # find the job # , e.g. [9]
84. fg 9 # type the # 9 from, the previous finding
85. bg 9 # put back to the background .
Now, you should try to find the process and kill it…
86. find . -name test.sh # locate test.sh from all sub-folders under
current dir
87. find . -print | grep -i lx # only list those files with “lx”
88. uptime
89. lscpu
90. ps ahuxf | sort | head -5 # short top 5 cpu usage processes
91. htop # show processes with top cpu usage ; you may need to
install it first
92. curl -O http://www.stormingrobots.com/prod/pdf/cs-syllabus.pdf
/mnt/c/your folder name here/Downloads/
93. ls -lt # check to see if you have downloaded cs-syllabus.pdf
94.
About redirection ( > )
95. echo Hello World 1. > test.txt
96. echo cat test.txt
97. echo Hello World 2. >> test.txt
98. echo cat test.txt
99. echo “hello” 1>/dev/null # suppress the standard output
Wish to redirect standout to a file:
⎯ runYourCommand &> file == redirect all the standard output (stdout, such as printf..) and
standard error (stderr, such as fprintf(stderr,... ) from your command to a file
Now, your history table should be very long.. Clear it up:
100. history -c
Created by Storming Robots
Elizabeth | STORMING ROBOTS Page 18 of 24
Linux Commands Exercises
PART I
1. Change your password. Logout and log back in. (don’t forget.. it will be multiple nuisance steps to do if
you lost it. ) 2. Change it back to what it was before.
S IMPLE STANDARD OUTPUT
1. Enter a command to print "Hello world" on the screen. 2. Display the current date and time on the screen.
F ILE PATHS AND FOLDER NAVIGATION
1. Display the full path of your home folder. 2. Go to your own windows user folder. Hint /mnt/c . 3. List all the files in your current folder. 4. List all the sub-directories and files in your current folder. 5. Go back to your linux home folder. (do it without typing full path) 6. Display the full path of current folder. 7. Create two new folders called “temp1” and “temp2”. 8. Create a file with content “hello world 1’ as temp1.txt under “temp1”. BUT, do that without going into temp1
folder. 9. Create a file with content “hello world 2’ as temp2.txt under “temp2”. BUT, do that without going into temp2
folder. 10. Take a look what is in the temp1, and temp2 folder 11. Copy the temp1.txt into ‘temp2” folder. 12. Take a look what is in the temp2 folder 13. List all the files in this folder. Use a more detailed listing where you can see the files' permissions, date written,
etc. 14. Change the time stamp for both files under temp1 and temp2. 15. List all the files in this folder. Use a more detailed listing where you can see the files' permissions, date written,
etc. 16. Go into temp1 folder, and create another called temp1_2., then go into this folder temp1_2. 17. Copy the file from temp2 into this new temp1_2 folder. 18. List all files to check that out to see the copy was successful. 19. Compare the file in temp1_2 against the temp2.txt in temp2 folder to ensure they are the same. 20. Go back home folder. 21. Capture the current full path (recursively) into a file called allMyTempfolders.txt. 22. Search recursively for any file with “temp in its file name. 23. Delete temp1 folder with a single command. (The command you use should also delete all of the files inside of
the folder.) 24. Rename temp2 folder to testDir. 25. Show the current path.
Created by Storming Robots
Elizabeth | STORMING ROBOTS Page 19 of 24
26. Clear the screen 27. Capture all the commands into a file called hw1.txt 28. Edit this hw1.txt to leave only the commands equivalent to this set of exercises. That means, remove all those
commands which do not apply. Therefore, there should be only 27 lines left in your hw1.txt file.
PERMISSIONS
1. Clear the history 2. Go to “testDir”, create a file called 'testFile' containing the text “It's a secret!” using the echo command. 3. Check out what is in your current folder using “ls”. 4. Do something to make this file hidden from the simple “ls” command. 5. Check out what is in your current folder using “ls” again. Can you see the test File that you just created? 6. Try to display the content of this test File using cat. What happen?
7. Change the permission of this file to non-readable. 8. Try to display the content of test File using cat. What happen?
9. Change the permission of this file to readable, but not writable. 10. Try to display the content of test File using cat.
11. Try to attach more content to the end of the file. What happen? 12. Delete this test file. 13. Capture all the commands into a file called hw2.txt 14. Edit this hw2.txt to leave only the commands equivalent to this set of exercises. That means, remove all those
commands which do not apply. Therefore, there should be only 12 lines left in your hw2.txt file.
PROCESS INFORMATION
1. Clear the past history 2. Enter a command to display the version of the Linux kernel that you are you using. 3. List all of the processes that are currently running. (with e a ) 4. Show the top linux processes 5. interactive linux process viewer 6. suspend (4) process 7. type “sleep 1000 &” 8. type “sleep 2000 &” 9. display the jobs which have been suspended 10. Display the process table in tree format 11. kill all these 3 processes.
SEARCHING
1. Use grep to display the entry with your username in the file '/etc/passwd'. 2. Capture all the commands into a file called hw3.txt 3. Edit this hw3.txt to leave only the commands equivalent to the set of exercises. That means, remove all those
commands which do not apply. Therefore, there should be only 13 lines left in your hw3.txt file. Go to next page ...
Created by Storming Robots
Elizabeth | STORMING ROBOTS Page 20 of 24
PART II
(credit: University of Washington – School of Computer Science and Engineering)
Use a text editor (nano or vi) to create a plain text file named hw4.txt containing answers to the following
questions:
1. Use the man pages to find out what wc does. Give a brief description of it here. What does the -l option for wc do?
2. Run wc on the folder '/etc/passwd' and copy and paste your findings. 3. What command would you use to a terminate (stop) a process? 4. What information does the environment variable $HOME store? (Hint: use 'echo $HOME' to investigate.) 5. List two other important environment variables on your computer and what they store. Why are these variables
important? 6. If you created a file 'bigredbutton' somewhere on your computer and couldn't remember what folder it was in,
what command could you use to find it? Just give the name of the command. You do not need to describe all of the necessary arguments.
7. How is the command in the answer to the previous question different from the 'which' command? 8. How does the command “echo Hello World! > something” differ from “echo Hello World!”? 9. Assume we have run the first echo command from the previous question and now we execute “echo more text
> something”. Describe what this does. 10. Now assume we have run the commands in the previous two questions and now we execute “echo yet more
text >> something”. Describe what this does.
Created by Storming Robots
Elizabeth | STORMING ROBOTS Page 21 of 24
Sample Scripting
Note: should always start the script with “#!/bin/bash”
SHOW HOW TO DO FACTORIAL OF A NUMBER USING “WHILE”
101. echo "do Fact ... "
102. echo "Enter a number: "
103. read num
104. fact=1
105.
106. echo "get Factorial($num) with while" #--------------------------------
----------
107. while [ $num -gt 1 ]
108. do
109. fact=$((fact * num))
110. num=$((num : 1))
111. done
112. echo $fact
SHOW HOW TO DO FACTORIAL OF A NUMBER USING “FOR”
113. for ((i=2; i<=num;i++)) {
114. fact=$((fact * i))
115. }
AUTOMATE A TEST WITH USACO’S #.IN TEST FILES
116. printf "runThis.sh <exeName> <max # test>...\n\n "
117. read exeName num
118. let i=1
119. while [ $((i)) -le $num ]
120. do
121. printf "test $i.in...\n"
122. cp $i.in $exeName.in
123. diff $i.out $exeName.out
124. i=$((i+1))
125. done
READ ONE LINE AT A TIME FROM A FILE.
126. #!/bin/bash
127.
128. echo "display the whole file-------"
129. cat file.txt
130.
Created by Storming Robots
Elizabeth | STORMING ROBOTS Page 22 of 24
131. echo "display whole file without linebreak------"
132. echo $(cat file.txt)
133.
134.
135. echo "display each word-------: "
136. for word in $(cat file.txt)
137. do
138. echo "$word"
139. done
140.
141. echo "display each line------: "
142. old_IFS=$IFS
143. IFS=$'\n' # new field separator
144.
145. for line in $(cat file.txt)
146. do
147. echo ":: $line"
148. done
149. IFS=$old_IFS
150.
151. echo "display each line use file redirect ------: "
152. while read line
153. do
154. echo -e ">> $line \n"
155. done < file.txt
Created by Storming Robots
Elizabeth | STORMING ROBOTS Page 23 of 24
FUNCTION SCRIPT SAMPLES
The following samples show how to read a number from a file.
Sample 1: passing in a string argument
61. doFact()
62. {
63. fname=$1
64. fact=1
65. echo "Read from file: $fname"
66.
67. read num < $1
68. # or
69. # num=$(cat $fname)
70.
71. echo "got $num"
72. for ((i=2; i<=num;i++))
73. {
74. fact=$((fact * i))
75. }
76. echo "$num! = $fact"
77. }
78.
79. doFact "1.in"
Created by Storming Robots
Elizabeth | STORMING ROBOTS Page 24 of 24
Sample2: passing in 2 arguments
More reference: Learn more on important Linux commands.
80. doFact()
81. {
82. num=$1
83. fact=1
84. echo "Read from file: $2"
85.
86. if [[ $2 = 1 ]]
87. then
88. echo "do while ... "
89. echo "get Factorial($num) with while"
90. while [ $num -gt 1 ]
91. do
92. fact=$((fact * num))
93. num=$((num - 1))
94. done
95. echo $fact
96.
97. else
98. echo "do for ... "
99. echo "get Factorial($num) with for"
100. for ((i=2; i<=num;i++))
101. {
102. fact=$((fact * i))
103. }
104. echo $fact
105. fi
106. }
107.
108. echo -e "do Factorial ...: e.g.\n func.sh (do
factorial using for)"
109. echo -e "\n func.sh 1 (do factorial using
while)\n\n"
110.
111. echo "Enter a number: "
112. read num
113. doFact $num "file.txt"