Search the Community
Showing results for tags 'beginners'.
-
Golang which is also called Go programming language is an open-source programming language designed by Google in 2007. Version 1.0 of this language was released in 2012. It is a structured programming language like C and different types of applications such as networking services, cloud applications, web applications, etc. can be developed by Golang language. It contains many types of packages like Python. It is very easy to learn, which makes this language popular for new programmers. 30 Golang programming examples have been explained in this tutorial to learn Golang from the basics. Pre-requisites: Golang is supported by different types of operating systems. The way of installing Golang on Ubuntu has been shown in this part of the tutorial. Run the following commands to update the system and install the Golang on the system before practicing the examples in this tutorial. $ sudo apt update $ sudo apt install golang-go Run the following command to check the installed version of the Golang. $ go version Table of contents: Golang hello world Golang string variables Golang int to string Golang string to int Golang string concatenation Golang multiline string Golang split string Golang sprintf Golang enum Golang struct Golang array Golang set Golang for loop Golang for range Golang while loop Golang continue Golang switch case Golang random number Golang sleep Golang time Golang uuid Golang read file Golang read file line by line Golang write to file Golang check if file exists Golang csv Golang yaml Golang http request Golang command line arguments Golang error handling Golang hello world The main package of Golang contains all required packages for Golang programming and it is required to start the execution of the Golang script. The fmt package is required to import for printing the formatted string in the terminal. Create a Golang file with the following script. The string value, ‘Hello World.’ will be printed in the terminal after executing the script. //Import the fmt package to print the output import "fmt" //Define the main() function to start the execution func main() { //Print a simple message with the new line fmt.Println("Hello World.") } Run the following command to execute the script. Here, the script has been saved in the example1, go file. $ go run example1.go Run the following command to build the binary file of the Golang file. $ go build example1.go Run the following command to run the executable file. $ ./example1 The following output will appear after executing the above commands,, Go to top Golang string variables The string variables can be used without defining the data type and with the data type in Golang. Create a Golang file with the following script that will print simple string data and the string data with the string variables. The uses of Printf() and Println() functions have been shown in the script. package main //Import the fmt package to print the output import "fmt" //Define the main() function func main() { //Print a string value with a new line fmt.Printf("Learn Golang from LinuxHint.com.\n") //Define the first string variable var str1 = "Golang Programming. " //Print the variable without a newline fmt.Printf("Learn %s", str1) //Define the second string variable var str2 = "easy to learn." //Print the variable with a newline fmt.Println("It is", str2) } The following output will appear after executing the above script. The output of the two concatenated strings are printed here. Go to top Golang int to string The strconv.Itoa() and strconv.FormatInt() functions can be used to convert the integer to a string value in Golang. The strconv.Itoa() is used to convert the integer value into a string of numbers. The strconv.FormatInt() function is used to convert decimal-based integer values into the string. Create a Golang file with the following script that shows the way of converting the integer to a string in Golang by using the functions mentioned above. A number will be taken from the user and the corresponding string value of the number will be printed as the output. //Add the main package package main //Import the fmt and strconv packages import ( "fmt" "strconv" ) //Define the main function func main() { //Declare an integer variable var n int //Print a message fmt.Printf("Enter a number: ") //Take input from the user fmt.Scan(&n) //Convert integer to string using Itoa() function convert1 := strconv.Itoa(n) fmt.Printf("Converting integer to string using Itoa(): %s\n", convert1) //Convert integer to string using FormatInt() function convert2 := strconv.FormatInt(int64(n), 10) fmt.Printf("Converting integer to string using FormatInt(): %s\n", convert2) } The following output will appear after executing the script. The number. 45 has been converted to the string. “45”. Go to top Golang string to int The strconv.Atoi() function is used to convert the string to an integer in Golang. It takes a string value that will be converted into an integer and returns two types of values. One value is the integer if the conversation is successful and another value is the error if the conversation is unsuccessful otherwise nil value will be returned. Create a Golang file with the following script that will convert a number of string values into an integer by using strconv.Atoi() function. The string value, “342” will be converted into 342 number and printed after the execution. //Add the main package package main //Import the fmt and strconv packages import ( "fmt" "strconv" ) //Define the main function func main() { //Declare a string variable str := "342" //Convert string to integer using Atoi() function price, err := strconv.Atoi(str) //check for error if err == nil { //Print the converted value fmt.Printf("The price of the book is %d\n", price) }else{ //Print the error message fmt.Println(err) } } The following output will appear after executing the script. The string value, “342” has been converted to 342 here. Go to top Golang string concatenation Create a Golang file with the following script that will concatenate the strings with the ‘+’ operator by using the Printf() function. The Println() function has been used here to print the concatenated string value by using the ‘+’ operator and Printf() function has been used here to print the concatenated string value by using the ‘%s’ specifier. Two string variables have been declared in the script which are concatenated later. //Add the main package package main //Import the fmt package to print the output import "fmt" //Define the main function func main() { //Declare two string variables var str1, str2 string //Assign string values str1 = " Golang" str2 = " Programming" //Concatenating string using '+' operator fmt.Println("Concatenated string value using '+' operator:", str1 + str2) //Concatenating string using '%s' specifier fmt.Printf("Concatenated string value using format specifier: %s%s\n", str1, str2) } The following output will appear after executing the script. Go to top Golang multi-line string Three different ways have been shown in the following example to print the multi-line text by using the Golang script. The ‘\n’ character has been used in the first string variable to generate the multi-line text. The backticks (`) have been used in the second string to print the multi-line text. The backticks (`) with specifiers have been used in the third string to print multi-line text. package main //Import the fmt package import "fmt" //Define the main function func main() { //Declare a multi-line string value with '\n' character str1 := "Golang programming\is very easy\nto learn.\n\n" fmt.Printf(str1) //Declare a multi-line string value with backticks(`) str2 := `Learn Golang from LinuxHint Blog.` fmt.Printf("%s\n\n",str2) //Declare two string values language := "Golang" developer := "Google" //Declare a string value with variables and backticks str3 := `%s is developed by %s.` fmt.Printf(str3, language, developer) //Add a new line fmt.Println() } The following output will appear after executing the script. The output of the three string variables that contain multi-line string values has been printed here. Go to top Golang split string The strings.Split() function has been used to split the string data based on the separator. The following script will take a string value from the user and split the string value based on the colon(:). The total number of split values and the first two split values will be printed after the execution. package main //Import the fmt and strings packages import ( "fmt" "strings" ) //Define the main function func main() { //Declare a string variable var str string //Print a prompt message fmt.Printf("Enter a string with colon(:)- ") //Take input from the user fmt.Scan(&str) //Define the separator separator := ":" //Split the string value split_value := strings.Split(str, separator) //Count the number of split values length := len(split_value) //Print the number of split values fmt.Printf("Total number of split values is %d\n", length) //Print the split values fmt.Println("The first split value is", split_value[0]) fmt.Println("The second split value is", split_value[1]) } The following output will appear after executing the script. The input value, “golang:google” has been divided into two parts based on the colon(:). Go to top Golang sprintf The Sprintf() function is used in Golang to store the formatted string values into a variable like other standard programming languages. A string and an integer variable have been declared in the following script. The values of these variables have been formatted and stored into a variable by using the Sprintf() function. package main //Import the fmt package import "fmt" //Define the main function func main() { //Declare two variables var str string var num int //Assign string value str = "Golang" //Assign number value num = 2012 //Store the combined string value in a variable combined_str := fmt.Sprintf("The first version of %s is released in %d.", str, num) //Print the variable fmt.Printf("The output of the Sprintf(): \n%s\n", combined_str) } The following output will appear after executing the script. Go to top Golang enum The enum or enumerator has been used in Golang to declare a data type of a group of related constant values. The declaration of enum type in Golang is different from other programming languages. An enum type of 12 values has been declared and the numeric value of the particular enum value has been printed later. package main //Import the fmt package import "fmt" //Declare the type to store the month value in number (1-12) type Month int //Declare constants for each month's value starting from 1 const ( Jan Month = iota + 1 Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ) //Declare main function func main() { //Declare variable with a month value var M_num = May //Print the corresponding number value of the month fmt.Println("The month value in number is ", M_num) } The following output will appear after executing the script. The corresponding numeric value of the May is 5. Go to top Golang struct The struct or structure is used in Golang to declare a type that contains different types of variables. It is useful for storing tabular data or multiple records. In the following script, a structure variable of four elements has been declared. Next, two records have been added by using the defined struct variable. The way of printing the values of the struct in different ways has been shown in the last part of the script. package main //Import fmt package import "fmt" //Define a structure of four elements type Product struct { id string name string size string price int } func main() { //Declare the first structure variable product1 := Product {"p-1209", "HDD", "5TB", 80} //Declare the second structure variable product2 := Product {"p-7342", "Mouse", "", 15} //Print the structure variables fmt.Println("First product: ", product1) fmt.Println("Second product: ", product2) //Print four values of the first structure variable separately fmt.Println("First product details:") fmt.Println("ID: ",product1.id) fmt.Println("Name: ",product1.name) fmt.Println("Size: ",product1.size) fmt.Println("Price: ",product1.price) } The following output will appear after executing the script. Go to top Golang array The array variable is used in Golang to store multiple values of the particular data type like other standard programming languages. The way of declaring and accessing an array of string values and an array of numeric values has been shown in the script. package main //Import fmt package import "fmt" func main() { //Declare an array of string values str_arr := [4] string {"google.com", "ask.com", "bing.com", "you.com"} //Print the array of string fmt.Println("String Array values are: ", str_arr) //Print the 3rd element of the array fmt.Println("The 3rd value of array is", str_arr[2]) //Declare an array of numeric values int_arr := [6]int{65, 34, 12, 81, 52, 70} //Print the array of integer fmt.Println("Integer Array values are: ", int_arr) //Print the 4th element of the array fmt.Println("The 4th value of array is", int_arr[3]) } The following output will appear after executing the script. Go to top Golang set The set is another data structure of Golang to store a collection of distinct values. It is used to store unique values in an object. Golang has no built-in set data structure like other programming languages. But this feature can be implemented by using empty struct{} and map. In the following script, a set variable of strings has been declared by using a map with the empty struct. Next, three values have been added, one value has been deleted, and one value has been added again in the set. The values of the set have been printed together and separately. package main //Import fmt package import "fmt" func main() { //Define a set of strings lang := map[string]struct{}{} //Insert three elements into the set using an empty struct lang["Go"] = struct{}{} lang["Bash"] = struct{}{} lang["Python"] = struct{}{} //Print the current existing elements of the set fmt.Println(lang) //Remove an element from the set delete(lang, "Python") //Add a new element to the set lang["Java"] = struct{}{} //Print the set values after removing and adding an element fmt.Println(lang) fmt.Printf("\nSet values are:\n") //Print each element of the set separately for l := range lang { fmt.Println(l) } } The following output will appear after executing the script. Go to top Golang for loop The for loop can be used in different ways and for different purposes in Golang. The use of three expressions for loop has been shown in the following script. The loop will be iterated 5 times to take 5 input values and the sum of these input values will be printed later. package main //Import fmt package import "fmt" func main() { //Declare an integer variable var number int //Declare a variable to store the sum value var sum = 0 //Define a for loop for n := 1; n <= 5; n++ { //Print a prompt message fmt.Printf("Enter a number:") //Take input from the user fmt.Scan(&number) //Add the input number with the sum variable sum = sum + number } //Print the summation result fmt.Printf("The sum of five input values is %d\n", sum) } The following output will appear after executing the script. The sum of 6, 3, 4, 7, and 9 is 29. Go to top Golang for range The range is used with the for loop in the Golang to access string, array, and map. The way of accessing an array of strings by using a for loop with range has been shown in the following script. The first for loop will print the array values only and the second for loop will print the indexes and values of the array. package main //Import fmt package import "fmt" func main() { //Declare an array of string flowers := [4] string {"Rose", "Lily", "Dalia", "Sun Flower"} fmt.Println("Array values are:") //Print the array values for _, val := range flowers { fmt.Println(val) } fmt.Println("Array indexes and values are:") //Print the array values based on index for in, val := range flowers { fmt.Printf("%d := %s\n", in + 1, val) } } The following output will appear after executing the script. Go to top Golang while loop Golang has no while loop like other programming languages. However, the feature of the while loop can be implemented in Golang by using the for loop. The way of implementing a while loop by using a for loop has been shown in the following script. The for loop will be iterated for 4 times and take four numbers. The sum of these numbers with the fractional value will be printed later. package main //Import fmt package import "fmt" func main() { counter := 1 sum := 0.0 var number float64 for counter <= 4 { //Print a prompt message fmt.Printf("Enter a number: ") //Take input from the user fmt.Scan(&number) //Add the input number with the sum variable sum = sum + number //Increment the counter by 1 counter++ } //Print the summation result fmt.Printf("The sum of four input values is %0.2f\n", sum) } The following output will appear after executing the script. The sum of 6.8, 3.2, 8.5, and 4.9 is 23.40. Go to top Golang continue The continue statement is used in any loop to omit the particular statements based on a condition. In the following script, the for loop has been used to iterate the loop that will omit the values of the 2nd and the fourth values of the array by using the continue statement. package main //Import fmt package import "fmt" func main() { counter := 1 sum := 0.0 var number float64 for counter <= 4 { //Print a prompt message fmt.Printf("Enter a number: ") //Take input from the user fmt.Scan(&number) //Add the input number with the sum variable sum = sum + number //Increment the counter by 1 counter++ } //Print the summation result fmt.Printf("The sum of four input values is %0.2f\n", sum) } The following output will appear after executing the script. Go to top Golang switch case The switch-case statement in Golang is similar to the other programming languages but no break statement is required with each case statement in Golang. The way of defining multiple case values inside the switch block has been shown in the following example. package main //Import fmt package import "fmt" func main() { var n int //Print a prompt message fmt.Printf("Enter the month value in number: ") //Take input from the user fmt.Scan(&n) //Print message based on the matching case value switch n { case 1, 2, 3, 4: fmt.Println("Winter semester.") case 5, 6, 7, 8: fmt.Println("Summer semester.") case 9, 10, 11, 12: fmt.Println("Fall Semester.") default: fmt.Println("Month value is out of range.") } } The following output will appear after executing the script. Go to top Golang random number The math/rand package has been used in Golang to generate random numbers. The way of generating four types of random numbers has been shown in the following script. The rand.Int() function is used to generate a long integer random number. The rand.Intn(n) function is used to generate an integer random number of the particular range and the highest value will be passed as the argument value of the function. The 999 is set as the argument value in the script. The rand.Float32() function is used to generate a short fractional random number and the rand.Float64() function is used to generate a long fractional random number. //Add main package package main //Import required modules import ( "fmt" "time" "math/rand" ) func main() { //Set seed to generate a random number rand.Seed(time.Now().UnixNano()) //Print generated random integer fmt.Println("Random integer value: ", rand.Int()) //Print the random integer within 999 fmt.Println("Random integer value with range: ", rand.Intn(999)) //Print the random 32 bits float fmt.Println("Random 32 bits float value: ", rand.Float32()) //Print the random 64 bits float fmt.Println("Random 64 bits float value: ", rand.Float64()) } The following output will appear after executing the script. Go to top Golang sleep The time.Sleep() function is used in Golang to pause the execution of the script for a certain period. The following script will calculate the average of three numbers and wait for 3 seconds before terminating the script. //Add main package package main //Import required packages import ( "fmt" "time" ) func main() { fmt.Println("Start executing the script...") //Define three variables a := 40 b := 30 c := 29 //Print the variables fmt.Printf("Three numbers are : %d, %d, %d\n", a, b, c) fmt.Println("Calculating the average of three numbers...") avg := (a + b + c)/3 //Delay for 3 seconds time.Sleep(3 * time.Second) //Print the results fmt.Printf("The average value is %d\n", avg) fmt.Println("Program terminated.") } The following output will appear after executing the script. Go to top Golang time The time package is used in Golang to read the current date and time. This package has many methods and properties to read the date and time in different ways. The date and time, ‘Mon Jan 2 15:04:05 -0700 MST 2006’ is used as the reference value in Golang to access the date and time. The uses of the time package have been shown in the following example. package main //Import required packages import ( "fmt" "time" ) func main() { //Read the current date and time today := time.Now() //Print the current date fmt.Printf("Today is %s.\n", today.Format("02-Jan-2006")) //Print the current date and time fmt.Printf("The current date and time is %s\n.", today.Format(time.RFC1123)) } The following output will appear after executing the script. Go to top Golang uuid The UUID or Universally Unique Identifier can be generated by Golang script. It is a 128-bit unique value to identify the computer system. You have to download the uuid from the github.com/google/uuid before executing the following script. Go to the home directory and run the following commands to download the required package to generate the uuid by Golang script. $ go mod init uuid $ go get github.com/google/uuid In the following script, the first uuid is generated by using the uuid.New() function that returns a unique identifier. The second uuid is generated by the uuid.NewUUID() function that returns two values. The value contains the unique identifier and the second value contains the error message if it exists. package main //Import required packages import ( "fmt" "github.com/google/uuid" ) func main() { //Generate a unique ID using New() function newID := uuid.New() fmt.Printf("Generated first UUID is %s.\n", newID) //Generate a unique ID using NewUUID() function newID, err := uuid.NewUUID() //Check for error if err == nil { fmt.Printf("Generated second UUID is %s.\n", newID) }else{ fmt.Println(err) } } The following output will appear after executing the script. Go to top Golang read file The io/ioutil package of Golang is used to read the content of a file. The ReadFile() function of this package reads the whole content of a file. This function returns the full content of the file into a variable if the file exists otherwise an error message will be returned. The way of reading the full content of an existing text file has been shown in the following script. //Add main package package main //Import required packages import ( "io/ioutil" "fmt" "log" ) func main() { //Read a text file text, err := ioutil.ReadFile("Languages.txt") //Check for error if err == nil { fmt.Printf("Content of the file:\n\n") fmt.Println(string(text)) }else{ log.Fatalf("File read error: %v", err) } } The following output will appear after executing the script. Go to top Golang read file line by line The “bufio” package of Golang is used to read the content of a file line by line. In the following script, the bufio.NewScanner() has been used to create an object to read the file. Next, the Scan() function has been used with the loop to read and print each line of the file. //Add main package package main //Import required packages import ( "fmt" "os" "bufio" ) func main() { //Open a text file for reading fh, err := os.Open("Languages.txt") //Check for error if err == nil { //Scan the file content read := bufio.NewScanner(fh) //Read the file line by line for read.Scan() { fmt.Println(read.Text()) } }else{ fmt.Println(err) } //Close the file defer fh.Close() } The following output will appear after executing the script. Go to top Golang write to file The os package of the Golang is used to open a file for writing and the WriteString() function is used to write content into a file. The way of creating and writing a text file of three lines is by using the os package. package main //Import required packages import ( "fmt" "os" ) func main() { //Open a file for writing fh, err1 := os.Create("items.txt") //Check for file creation error if err1 == nil { //Write into the file _, err2 := fh.WriteString("Pen\nPencil\nRuler\n") //Check for file writing error if err2 != nil { fmt.Println("File write error occurred.\n") } }else{ fmt.Println("File creation error occurred.\n") } //Close the file defer fh.Close() } The following output will appear after executing the script. The output shows that the items.txt file has been created successfully. Go to top Golang checks if file exists The os package of the Golang can be used to check the existence of the file. In the following script, the file path will be taken from the script. If the path does not exist then the os.State() function will return an os.ErrNotExist error. package main //Import required module import ( "errors" "fmt" "os" ) func main() { var filepath string fmt.Printf("Enter an existing filename: ") //Take the file path from the user fmt.Scan(&filepath) //Check the file path _, error := os.Stat(filepath) //Check the output of the os.Stat if !errors.Is(error, os.ErrNotExist) { fmt.Println("File is found.") } else { fmt.Println("File is not found.") } } The following output will appear after executing the script. Go to top Golang csv The “encoding/csv” package is used in Golang to read the content of the CSV file. The csv.NewReader() function is used to read the CSV file. Create a CSV file before executing the script of this example. Here, the customers.csv file has been used to show the way of reading the CSV file. package main //Import required packages import ( "encoding/csv" "fmt" "os" ) func main() { //Open a CSV file for reading fh, err := os.Open("customers.csv") //Check for the error if err != nil { fmt.Println(err) }else{ //Create an object to read the CSV file scanner := csv.NewReader(fh) //Read all records of the CSV file records, _ := scanner.ReadAll() //Read the CSV file line by line for _, r := range records { for _, c := range r { fmt.Printf("%s,", c) } fmt.Println() } } //Close the file defer fh.Close() } The following output will appear after executing the script. Go to top Golang yaml The yaml.Marshal() function is used in Golang to read the content of the yaml data. You have to download the yaml package to use the yaml.Marshal(). Go to the home directory and run the following command to download the yaml package. $ go get <a href="http://gopkg.in/yaml.v2">gopkg.in/yaml.v2</a> In the following script, a structure variable of four elements has been declared that has been used later to define a yaml object with data. Next, the yaml.Marshal() function has been used to access the yaml data. package main //Import required packages import ( "fmt" "gopkg.in/yaml.v2" ) //Declare a structure of 4 elements type Book struct { Title string Author string Publication string Price string } func main() { //Create an object of the structure book1 := Book{ Title: "Learning Go", Author: "John Bodner", Publication: "O'Relly", Price: "$39", } //Read the yaml data based on the struct y_data, err := yaml.Marshal(&book1) //Checkk for the error if err == nil { //Print the yaml data fmt.Println(string(y_data)) }else{ fmt.Printf("Error while Marshaling. %v", err) } } The following output will appear after executing the script. Go to top Golang http request The net/http package of the Golang is used to send the http requests to a website. The http.Get() function is used to send the request. It returns the response from the site or the error message. The way of sending the http request to the website, https://example.com has been shown in the following script. package main //Import required packages import ( "fmt" "net/http" ) func main() { //Send a GET request to a website res, err := http.Get("https://example.com") //Check for error if err == nil { //Print the response sent by the website fmt.Println(res) }else{ //Print the error message fmt.Println(err) } } The following output will appear after executing the script. Go to top Golang command line arguments The values that are passed at the time of the execution of the script are called command-line argument values. The os package is used to read the command line argument values in Golang. The argument values are stored in the Args[] array. The for loop with the range has been used in the script to print the argument values without the script name in each line. package main //Imports required packages import ( "fmt" "os" ) func main() { fmt.Println("All argument values are:") //Print all argument values with the script name fmt.Println(os.Args) fmt.Println("Argument values:") //Print all argument values without a script name for in, _ := range os.Args { if in == 0 { continue } fmt.Println(os.Args[in]) } } The following output will appear after executing the script. Go to top Golang error handling Golang has no try-catch block like other programming languages. However, the errors package can be used in Golang to handle errors in the script. In the following script, an integer number will be taken from the user. If the user takes a negative number then an error message will be printed. The errors.New() function has been used here to generate the error message. package main //Import required packages import ( "errors" "fmt" ) func main() { var n int fmt.Printf("Enter a number: ") fmt.Scan(&n) //Check the input value result, err := Positive(n) //Check for error if err != nil { fmt.Println(err) } else { fmt.Printf("%d %s\n", n, result) } } ///Define function to check positive number func Positive(num int) (string, error) { if num < 0 { return "", errors.New("Type a positive number.") }else{ return "number is positive.", nil } } The following output will appear after executing the script. Go to top Conclusion: Golang is a popular programming language now that has many useful packages like the Python programming language. Any novice user can learn Golang as a first programming language because it is very easy to learn. The basic 30 Golang examples have been explained in this tutorial to learn Golang from the beginning and the learners will be able to write programs in Golang. One of the major limitations of this language is that it does not contain the features of object-oriented programming but it is good for learning structured programming. View the full article
-
Are you looking to make a career in data science? Start by learning SQL with these free courses.View the full article
-
- sql
- data science
-
(and 5 more)
Tagged with:
-
I am new to AWS, can someone tell me how to connect to AWS.
- 1 reply
-
- aws ec2
- aws connectivity
-
(and 1 more)
Tagged with:
-
The post Cheat – The Ultimate Linux Commands Cheat Sheet for Beginners and Administrators first appeared on Tecmint: Linux Howtos, Tutorials & Guides .What you do when you are not sure of the command you are running especially in case of complex Linux commands which use a lot The post Cheat – The Ultimate Linux Commands Cheat Sheet for Beginners and Administrators first appeared on Tecmint: Linux Howtos, Tutorials & Guides.View the full article
-
- cheatsheets
- linux
-
(and 2 more)
Tagged with:
-
What is VirtualBox? VirtualBox (VB) is a cross-platform hypervisor or virtualization software developed by Oracle Corporation. Basically, VB allows user to run guest operating system on another host operating system virtually without need for partitioning of hard drive or running another OS on dual boot which involves risk of crashing host system. VirtualBox creates virtual hard drive and installs guest OS on it. Virtual hard drive is nothing but the big size file stored on the computer hard drive. This file works as a real hard drive for the guest OS. Running any application software or video game on virtual machines is sometimes not as smooth as running them on OS installed on full hardware. Everything depends on amount of hardware resource allocated to virtual machine. Why to Use VB? I know many of us have heard of VirtualBox but always have apprehensions of trying or using it just because we think it is a messy task to setup Virtual Machine and it might harm our whole computer system. However, it is the misconception because setting up virtual machines is easy and it won’t affect your computer system if you setup it correctly. VirtualBox can be very useful for people like me who always like to try and mess with different application software’s and operating systems because: It can also be very useful tool for application developers who can test their application on different platform before releasing it for public. Software reviewers like me can also use this to try and test software’s on different platforms under one single window. Installation First, head over to downloads page on VirtualBox’s official website and download the installation package depending on your operating system. I am going to install virtual box on latest Microsoft Windows 11. So, I will download virtual box installation file for Windows. Once the downloading is complete, run the installation file and follow the steps as the installer guides you through the installation process. You do not need to change anything during installation. So, just click Next every time it asks for and finish the installation. Once the installation is complete, start the VirtualBox from the desktop or Start Menu and the home screen will appear as shown below. Setting Up VirtualBox for Ubuntu Installation Now, we will see how to setup Virtual Machine for installing Ubuntu on VirtualBox. You can follow these steps to install Windows 10, Mac OS, and others too. Create Virtual Machine To start, click on the NEW button on the top of VirtualBox’s home screen. Then, Create Virtual Machine window will appear where you will have to give Virtual Machine a name like Ubuntu. Then, select the type and version of operating system you are going to install. Here, I have 64 bit ISO file so I selected 64 Bit version. I am going to install Ubuntu 22.04 LTS (Long Term Support) edition which is 64-bit operating system. RAM Allocation Click Next. Then, you will be asked for RAM allocation. Always remember, allocate more than half of your total RAM memory else it will affect your computers performance and in some cases, it might crash host system. I have total 8 GB of RAM, so I will allocate 1 GB i.e., 1024 MB which should be enough to run Ubuntu. According to your usage, you can allocate preferred RAM size for your virtual machine. Again, click Next. Then, it will ask you to create Virtual Hard Disk. Set Up Virtual Hard Disk Now, you will need to create Virtual Hard Disk to store VM data. Just select Create a virtual hard disk now option and click on Create button. On the following screen, you will be asked to choose Hard disk file type. Just select VDI (VirtualBox Disk Image) and click on Next. On the next screen, you will be asked whether to create a dynamically allocated or fixed size hard disk. If you want VM to always perform smoothly, then you should select fixed size where you will have to set size of the hard disk. But it will consume more disk space for better performance. With dynamically allocated disk, you will have to set maximum disk size but file will not consume more than allocated disk space. If you want VM with high performance, then select Fixed size and then click Next. Then, you will need to select the size of virtual hard disk. Selecting disk size always depends on how you are going to use VM. If you are going to install lot of applications on Ubuntu for various purposes, then you will need to allocate at least 25GB of disk space else you can allocate less space too. Here, I am selecting only 10 GB because I am creating this virtual machine for this tutorial. Then, click on Create and you are ready to install Ubuntu on Virtual Machine. As shown in above screenshot, you can see Ubuntu VM is added on VirtualBox. Before we start Ubuntu installation, we need to tweak some settings to ensure Ubuntu VM performs at its best. Click on Settings button then the following window will appear. Head over to Processor tab under System menu. Here, increase Processors value to 2 and click OK. Now, select Motherboard tab where under Boot Order, you will notice Floppy set on highest priority. Now, unselect Floppy and move Optical to top using Arrow button. Set the priority for Optical and Hard Disk as shown in the screenshot below. Then, select Display menu. Under Screen tab, you will have to allocate full Video Memory i.e., 128MB. Also, mark the checkbox next to Enable 3D Acceleration and Enable 2D Video Acceleration. Now, we will mount .iso file for Ubuntu installation. To do that, go to Storage menu where you will notice Empty disk under Controller: IDE, select Empty. Besides that, from the Optical Drive, drop down click on Choose Virtual Optical Disk File and find your Ubuntu installation file. You can download Ubuntu installation .iso file from here. Now, you can see VBoxGuestAdditions.iso disk is created in place of Empty disk. Finally click OK and you are good to go with Ubuntu installation. Now, we will start with Ubuntu installation. This process is not any different to normal OS installation we do using installation media or bootable pen drive. Installing Ubuntu 22.04 LTS on Virtual Box To start, click on the Start button on VirtualBox home screen. This will initiate the first boot of Ubuntu. Next, you will be asked to Try Ubuntu or Install Ubuntu. You just need to click on Install Ubuntu. On the next screen, you need to select your preferred language and head over to next screen, which is Updates and Other Software. Select Normal Installation and click on Continue button. Next, select your time zone and on the next screen you will be asked to provide user details. Insert the details and click on Continue. Now, Ubuntu installation will start. Wait for the installation to complete. Once the installation is complete, you will be asked to restart the computer. Just click on the Restart Now button and VB will do the rest. Latest Ubuntu 22.04 LTS is now successfully installed on Virtual Machine. Install Guest Additions To enable all the features of VirtualBox, you need to install the Guest Additions in Ubuntu. Select Devices tab from VirtualBox’s window and click on Insert Guest Additions CD image. Prompt will appear on Ubuntu screen asking you Would you like to run it? Click Run and enter password to Authenticate. Then, Terminal window will open up and it will perform some installation automatically. When you will see Press Return to close this window… press Enter to finish the setup. You are done with all the setup and now you can enjoy Ubuntu inside your Windows. All the steps and process are performed on Windows 11 and Ubuntu 22.04 LTS. You can follow same steps on older Windows and Ubuntu versions also. View the full article
-
- beginners guides
- beginners
-
(and 2 more)
Tagged with:
-
Open Web Application Security Project (OWASP) is a nonprofit foundation that is dedicated to improving web applications security. The vibrant OWASP community has projects, forums, and events aimed at increasing the members’ security preparedness.View the full article
-
Forum Statistics
63.6k
Total Topics61.7k
Total Posts