Assignment 3
Assignment 3
Assignment 3
Save and quit the file. Next, you need to make this file executable using the below command:
$ chmod 755 hello-world.sh
Now, you can run this script using any of the below two commands:
$ sh hello-world.sh
$ ./hello-world.sh
2. Defining Variables in a Bash Script
Variables in shell scripting are containers for storing necessary information. In Bash Script,
declare a variable by assigning a value to its reference by = operator. Furthermore, print the
assigned values using echo $(VARIABLE_NAME).
Example:
#!/bin/bash
# Declaration of variables
name=Tom age=12
# Displaying variables
echo $name $age
Output: Tom 12
The read command used with option -p allows you to prompt a message along with taking user
input. You can use echo $(VARIABLE_NAME) to display the user input on the screen.
Output:
Enter a number: 12
The number is: 12
By changing the IFS, you will be able to access values separated by your desired delimiter.
First, store the default IFS in a variable using old_IFS = $IFS. Now, change IFS according to
your preference and complete the task. At the end, restore the original IFS using IFS =
$old_IFS. The below script shows how:
#!/bin/bash #store
default IFS
old_IFS= $IFS
IFS=,
read val1 val2 val3 <<< "5,60"
echo 1st value: $val1 echo 2nd
value: $val2
#restore default IFS
IFS= $old_IFS;
Output:
1st value: 5
2nd value: 60
#!/bin/bash
for (( counter=1; counter<=10; counter++ )) do
echo -n "$counter "
done
#!/bin/bash counter=0
while [ $counter -le 10 ] do
echo Number: $counter ((counter++))
done
Let us say a file is located in a directory called /place/with/the/file. Then to add this path to the
$PATH variable use the following command:
export PATH=$PATH:/place/with/the/file
NOTE: If you are using Google cloud shell then for downloading any file to the local system
use the following command: cloudshell download <filename> Final Task for submission:
1. Using vim editor to write and save a simple shell script that outputs “Shell scripting
is an awesome way to carry out complex tasks easily.”
2. Make the script executable by changing its permissions using chmod command (chmod
755 will allow everyone to execute the script).
3. To run the script just by entering its name on the terminal, change the PATH variable
to contain the location of your present working directory.