Linux Bash Script That Reads Csv Files
Bash script programming is a sequence of executable commands, carrying out numerous commands at once, task performance automation, and authoritative tasks customization. Generally, all Linux users must acquaint themselves with the bones noesis of fustigate script programming because of the importance information technology offers.
Effective interaction with the control line is among the essential aspects that bash scripting provides. This means that the user tin can efficiently run executable commands. This eases the stress of having to comport out tasks manually.
35 Fustigate Script Examples
This article will run you through the core nuts that you need to know to become started with bash scripting. Let's have a look at the 35 Fustigate script examples:
1. First Bash Program
To get a fustigate file up and running, you need to execute information technology by running a last command. For instance, if we run "Hullo World" in our final, the output we go will be "Hullo World."
To create a bash file, you tin apply any text editor installed in your operating organization. In this example, nosotros will use the nano editor for creating the file. Let us name our file 'Commencement.sh'. Execute the command using the post-obit control:
nano First.sh
Add together the post-obit bash script to the file before saving the file.
#!/bin/bash echo "Hello World"
At that place are different ways of running bash commands. For example, beneath are two distinct examples of executing bash.
./First.sh
Alternatively, you lot can use execute the control below:
chmod a+x Outset.sh ./Commencement.sh
ii. Echo commands
repeat commands have numerous options for selection. For instance, there is an add-on of a new line by default if you use the 'echo' command without any other option. Alternatively, you lot can use '-n' to print whatever text without a new line. Make use of the '-e' control to remove backslash characters from the given output. To demonstrate this, create a bash file named 'echo_example.sh'. Subsequently that, add the script below
#!/bin/bash Echo "press text with newline" Echo -northward "printing text without newline" Echo -eastward "\nRemoving \t backslash \t characters\
Later on adding the script, execute the file with the control below:
bash echo_example.sh
three. Employ of annotate
While using comments, we utilise the "#" symbol to add a single line comment in bash scripting. Here, you will create a new file with a simple name such equally 'comment_example'. Include a script with a unmarried comment similar the example displayed below.
#!/bin /bash # Add 2 values ((sum thirty+20))
#thereafter impress the result echo $sum
execute the file with bash command-line
4. Multiline comment
In bash, the multiline comment is applicable in different ways. To prove this, create a new bash named, 'multiline-comment example.sh', after that, add ':' and " ' " scripts symbols to add together a multi-line annotate in the script. The following case will execute the square of 2.
#!bin/bash : ' The script written below is used to calculate the square of ii ' ((surface area=2*two)) repeat$area execute the file with bash command-line
bash multiline-comment-example.sh
five. While Loop
For piece of cake comprehension of this bash script, create a file named 'while_sample.sh'. The while loop will repeat 5 times before terminating the process. While looping, the count variable increases the count by 1 in every step till the fifth time when the loop stops.
#!/bin/fustigate valid=True count=1 while [$valid ] practice echo $count if [$count -eq 5 ]; then intermission fi ((count++)) done
execute the file with bash command-line
bash while_example.sh
6. For Loop
Take a look at the following for loop case. After creating a file named 'for_sample.sh', add the script using 'for loop'. This procedure will re-occur 12 times. After that, it will display the fields in a unmarried line, as shown below;
#!/bin/bash for (( counter=10; counter>0; counter-- )) do echo -n "$counter " done printf "\north"
Execute the command by running the code below
bash for_sample.sh
vii. Become User Input
To go user input from bash, we will use the 'read' command. Follow the simple steps below to achieve the expected results. Outset, create a file named 'user_feedin.sh' and include the script below to go the user input. One value volition be taken and displayed by combining other string values. Every bit indicated below,
#!/bin/bash repeat "Enter Your Proper noun" read name echo "Welcome $name to FossLinux"
execute the file with bash command-line
bash user_feedin.sh
8. If statement
The if statement is used by both multiple and unmarried weather. A definition of 'if' and 'fi' are used Before and afterward an if statement. To easily understand the if statement in bash, nosotros shall use an example. Create a file named 'example_if.sh'.
For instance, the number iv is assigned a variable 'due south.' If the number is divisible by ii, then the output will be "it is divisible by 2"; otherwise, if the number is not divisible past 2, then the result will be "information technology is not divisible by 2". The '-lt', in this instance, is used for comparison purposes. Another comparing characteristic is '-eq.' '-ne', on the other paw, is used to show inequality while '-gt' shows if a value is more significant in bash script.
#!/bin/bash s=4 if [ $due south / 2 ]; then echo "Information technology is not divisible by 2" else echo "Information technology is divisible by two" fi
execute the file with bash command-line
bash example_if.sh
9. Utilize of if argument together with AND logic
Diverse logical conditions tin can be used with the if argument whenever there are two or more conditions. The example below shows how the logic "AND" is used in defining multiple weather condition in an if statement. The "&&" symbols represent the "AND" logic in a bash script. Create a file named 'if_plus_AND.sh'.
In this example, the username and countersign variables entered by the user will be compared with the "main" and "users" directory to see if they match. If they practise, the process will be successful, thus displaying "valid-user" equally the output. Otherwise, if they practise not friction match, the outcome will be "invalid user."
!/bin/bash
echo "input username" read username echo "input password" read password
if [[ ( $username == "main" && $password == "users" ) ]]; and so repeat "valid user" else echo "invalid user" fi
Execute the file using the bash command-line
bash if_plus_AND.sh
The offset case shows hallmark failure since the user-provided does non friction match with the main fields.
The 2nd examples show successful authentication since the provided fields matched with the main fields.
x. Utilize if statement with OR logic
When using OR with the if role, the '||' symbol is used. To demonstrate this, nosotros will create a file named 'if_with_OR.sh' to check the use of OR logic in an IF statement. Take an instance of value 's' beingness assigned to two numbers (10 or twoscore). If a user inputs either of the given numbers, then the system's output will be "Well Played"; otherwise, the result shown will exist "Sorry, You Failed." If yous examine this example, you will notice that the value of s is generated from the user.
#!/bin/bash repeat "Enter any number" read south if [[ ( $s -eq ten || $n -eq 40 ) ]] and then echo "Well Played" else echo "Sorry, Y'all Failed" fi
execute the file with fustigate command-line
bash if_with_OR.sh
Every bit indicated in the example above, 5 is not equal to 10 or twoscore. Therefore, the output displays "Sorry, You Failed,"
In the figure to a higher place, the user was prompted to enter any number, and he/she chose 10, and the output given is "Well Played" since 10==10
11. Use of else if statement
Many conditional statements are nearly the same despite the programming languages you cull. However, in bash programming, the use of the 'else if' condition is kind of dissimilar. In fustigate, Elif is used in place of the else if condition. We volition create a file named 'elseif_instance.sh' then add the bash script for demonstration purposes.
echo "Enter your lucky number" read n if [ $north -eq 50 ]; then echo "Y'all won the 1st bravo!!!!" elif [ $n -eq 100 ]; then echo "You won the 2nd congrats!!!!" elif [ $n -eq 500 ]; so echo "You lot won the third congrats!!!!" else echo "Sorry, you have to keep trying pal" fi
Execute the file with bash command-line
Fustigate elseif_instance.sh
The execution above displays the three instances washed by bash.
12. case statement
Accept you ever heard of the "if-elseif-else" argument? If not, don't worry, equally it will be covered here. The Instance statement is used as a substitute for the if-elseif-else statement. 'Case' and 'esac' delineate the starting and catastrophe block respectively while using this statement. For more elaboration, an case will be of great help. Create a file named 'case_example.sh'. After that, include the script provided below. Then, take a look at the output and compare it to the previous 1. You will discover that the outcomes of both the example statement and if-elseif-else statements are the same.
#!/bin/fustigate echo "Input your Lucky Number" read south instance $due south in l) echo echo "You lot won the 1st bravo!!!!" ;; 100) repeat "You won the second congrats!!!!" ;; 500) echo "You won the tertiary congrats" ;; *) echo "Sorry, you have to keep trying pal" ;; esac
execute the file with bash command-line
bash case_example.sh
13. Obtaining arguments from Control Line
Fustigate script can emulate how other programming languages obtain inputs from the command line. Look at an instance where variables $1 and $3 are used to null through the first and third command-line arguments, respectively. For more elaboration, permit'due south create a file named 'command-line.sh' and include the script below. In the cease, the output given is the print of the total count of arguments read by the script.
#!/bin/bash repeat "Total arguments : $#" echo "1st Argument = $1" echo "third argument = $three"
Execute the file with bash command-line
bash command_line.sh Foss Linux Website
fourteen. Obtain arguments from command-line with names
This section demonstrates how to read command-line arguments that contain names. To do this, create a file named 'command_line_names.sh'. After that, add a code with two arguments: A, B, to be read by the script and compute the sum of A and B.
#!/bin/bash for arg in "$@" practise alphabetize=$(echo $arg | cutting -f1 -d=) val=$(echo $arg | cut -f2 -d=) case $index in A) a=$val;;
B) b=$val;;
*) esac washed ((result=a+b)) echo "A+B=$result"
Execution with bash command. The code below is a combination of the 2 command-line arguments.
bash command_line_names.sh A=x B=xvi
fifteen. Integrated string variables
Bash has some pregnant advantages that assistance a programmer to achieve tasks quickly. String variable integration is a combination of two or more than variables. To demonstrate this, create a file named 'string_combination.sh'. After that, add together the script provided below and look at how you tin integrate string variables by placing variables together using the '+' operator.
#!/bin/bash stringA="Foss" stringB="Linux" echo "$stringA$stringB" stringC=$stringA+$stringB stringC+=" has the best online tutorials" repeat $stringC
execute the file with bash command-line
fustigate string_combination.sh
xvi. How to Obtain a substring of string
Bash lacks an inbuilt function to truncate values from a information string, but similar other programming languages. Notwithstanding, fustigate allows you to carry out substring truncation differently, as shown in the script below. Create a file named 'substring_example.sh'. In this case, the value seven shows the substring's protrusive point, whereas 6 shows the substring'southward total length.
#!/bin/fustigate Str="Get connected to FossLinux blogsite" subStr=${Str:4:nine} repeat $subStr Execution with fustigate command
bash substring_example.sh
17. Addition of two numbers
Fustigate supports arithmetic operations in various and complex ways. To brandish the complex advantages of bash, you will do the sum of 2 integers using double brackets, as shown beneath. First, y'all will create a file named 'sum_numbers.sh' using the code below. The function will prompt the user to enter the first digit, then the second digit, and finally, print the issue, which computes the user'due south two integers.
#!/bin/bash echo "input get-go digit ane" read a echo "input digit 2" read b (( sum=a+b )) echo "Event=$sum"
Execute the file with bash command-line
bash sum_numbers.sh
18. function cosmos
Bash scripting allows the user to create a function and call the aforementioned role. This has been demonstrated in the example below. Create a file named 'function_example.sh' and input the lawmaking outline in the sample. Here, you volition select whatsoever role randomly by proper noun without specifying whatever kind of fustigate script brackets.
#!/bin/bash office x() { echo 'I love fosslinux' } ten
Execute the file using the command-line below;
bash function_example.sh
xix. Functionality cosmos with parameters
In bash programming, you can utilise parameters in a office by using other variables. Call the 1st value $i and the second value $ii in an instance where the two values are chosen simultaneously with the function to read the values. To define this, you lot will create a file named 'function_parameter.sh'. Permit usa find the area of a rectangle 'Rectangle_Area' using the given parameters.
#!/bin/bash Rectangle_Area() { area=$(($1 * $two)) repeat "Area is : $area" } Rectangle_Area 15 25 Execute the file with the fustigate control.
bash function_parameter.sh
20. Passing a return a value from a function
When dealing with returning values in bash programming, bash has a built-in function that allows the passing of numeric and string values. The following example shows the passing of string values in a office. You will create a file named 'function_return.sh' and include the lawmaking below for easy comprehension. The part grow() returns a cord value into the variable, which after outputs the integrated string results.
#!/bin/bash part greeting() { str="Goodmorning, $fname" echo $str } echo "Input your fname" read fname val=$(greeting) echo "Return value of the part is $val" Execute the file with bash command-line
bash function_return.sh
21. Make Directory
'Mkdir' is a command used to create a new directory. This control means 'make directory'. Create a file named 'make_directory.sh'. Later on that, input a code that will create a new directory. Bash will create a new directory for yous.
#!/bin/bash repeat "Input a new directory name" read newdir `mkdir $newdir`
Execute the file with bash command-line
bash make_directory.sh
22. Creation of a directory by checking its existence
'-d' is a command that aids the user to bank check for an existing directory in the current computer location or not. This prevents one from executing the 'mkdir' command when not sure whether a directory is there or non. For sit-in, create a file named 'directory_exists.sh' and add together the code written below to check any directory exists.
#!/bin/bash echo "New directory proper name input" read ndir if [ -d "$ndir" ] and so echo "The Directory given exists" else `mkdir $ndir`echo "Directory created" fi
Execution with bash control.
Fustigate directory_exists.sh
23. Reading a file
Bash has a looping functionality that helps the user to read any file. Here we will showcase the easiest way to make you empathise. Nosotros will do so past creating an example file named 'read_file.sh' and add the code beneath to determine the existing file called 'langeages.txt.'
#!/bin/bash file='languages.txt' while read line; do repeat $line washed < $file
Execute the file with bash command-line
bash read_file.sh
To check the original content of languages.txt, run the control beneath.
cat languages.txt
24. File Deleting
In bash programming, an 'rm' command is used to remove or delete files. We volition delete a file using the 'rm' command. First, create a file named 'delete_file.sh'. After that, use the lawmaking highlighted below to make the initial user's file proper name and remove it. The '-i' control is helpful as it allows the users to delete the file.
#!/bin/bash echo "Insert a filename to delete" read filename rm -i $filename
Execute the file with bash command-line.
bash delete_file.sh
25. Append or adding to file
With an existing file, fustigate has a '>>' operator that allows appending of new data into the file. To exam this, create a file named 'add_file.sh'. So add a code that will add information to the cease of the electric current file. Add the following string, 'studying angular,' to the 'languages.txt' file after running the bash script.
#!/bin/bash echo "Before adding the file" true cat languages.txt repeat "Studying athwart">> languages.txt echo "After adding the file" true cat languages.txt
Execution with bash command.
bash add_file.sh
26. Test File existence
Bash has great user functionalities that get in user-friendly. In this section, nosotros will see the functionality that gives you an choice of checking whether a particular file exists or not. The '-e' or '-f' commands will assist u.s. in checking if a file exists or not. To test this, create a file named 'file_exist.sh', and then add together the code below. In this exam, the filename will pass from the command line.
#!/bin/fustigate filename=$ane if [ -f "$filename" ]; then echo "File exists" else echo "File does not be" fi
Run the commands displayed beneath to ostend the existence of the files. In this case, the languages.txt file is available, whereas the languages1.txt file does non exist.
ls bash file_exist.sh languages.txt bash file_exist.sh languages1.txt
These commands are used to check whether a file existence looked for exists or non. For example, in this case, the languages.txt file exists, while the languages1.txt does not exist.
27. Transport E-mail
The 'mail' or 'sendmail' commands in a bash script are used to send emails. These commands volition work efficiently afterwards installing all the necessary packages. For sit-in purposes, create a file named 'mail_example.sh'. Use the codes highlighted below to send the intended email.
#!/bin/bash Recipient="fosslinux@example.com" Subject="inquiries" Bulletin="Need anything from fosslinux blogsite?" `mail -s $Bailiwick $Recipient <<< $Message`
Execute the file with the bash command.
bash mail_example.sh
28. Parse Current Appointment
Fustigate has a feature that enables parsing of the appointment and time values that we volition focus on in this section. Bash allows you to get the current appointment and time using the 'date' command. 'South,' 'd', '1000,' 'm', 'Y,' and 'H' are values used to analyze date and time. Create a file named 'date_parse.sh' and add a lawmaking that will detach month, year, day, 60 minutes, minutes, and the seconds' values.
#!/bin/bash Year=`date +%Y` Month=`date +%thousand` Day=`appointment +%d` Hour=`date +%H` Minute=`engagement +%Thou` 2nd=`date +%Due south` echo `date` echo "Electric current Date is: $Mean solar day-$Month-$Yr" echo "Current Time is: $Hour:$Minute:$2nd"
Execute the file with the bash command.
fustigate date_parse.sh
29. The Look command
Linux Os has a born command feature that awaits to complete whatever running procedure by using a peculiar id to finish that particular assigned job. Therefore, when there is no job id, the expect control volition wait for all secondary cycles to complete before returning exiting. Create a file named 'wait_example.sh' and add together the script below for execution.
#!/bin/bash echo "Waiting command" & process_id=$! await $process_id echo "Exited with condition $?"
Execute the file using the bash control.
bash wait_example.sh
xxx. The Sleep Control
The sleep control helps the user to interruption an ongoing task for a specified period. It gives you the allowance of delaying or halting/pausing for hours, minutes, seconds, or days. For illustration purposes, create a file and name it 'sleep_examples.sh', thereafter run the script shown beneath.
The case aims to filibuster the job for approximately 8 seconds after execution.
#!/bin/bash
echo "Please exist patient for 8 seconds" sleep viii echo "Completed"
Execute the file using the fustigate control
bash sleep_examples.sh
31. The AND Operator
This operator allows the system to cheque if multiple weather condition have been satisfied. This means that all conditions separated by the AND operator must exist true for correct execution. Additionally, the '&&' operator is used to announce 'AND'. To ascertain this, bank check the example below. Starting time, create a file chosen 'And_operator.sh' and so execute it using bash command-line.
#!/bin/bash echo -n "Input a Number:" read num
if [[ ( $num -lt xx ) && ( $num%two -eq 0 ) ]]; then echo "It is an Fifty-fifty Number" else echo "It is an Odd Number" fi
Execute the file using the bash control-line
bash And_operator.sh
32. The OR Operator
This is a great bash scripting construct that aids in creating complex logic in scripts. This construct works slightly differently than the 'AND' operator because it either returns true whenever the operands upshot is truthful. On the other hand, the 'or' operator only returns simulated whenever both the operands are false. Check the sample below for more than elaboration. To notice out virtually this construct, create a file named 'OR_operator.sh' and complete its execution using the command line.
#!/bin/bash
repeat -n "Enter whatever number:" read north
if [[ ( $northward -eq 5 || $northward -eq 30 ) ]] then echo "You won" else repeat "Y'all lost!" fi
Control-line execution using bash
fustigate OR_operator.sh
33. The switch construct
The Switch construct is applicable in situations where nested conditions are needed. The example below gives a detailed outline. Create a file named 'switch_construct.sh'. So execute the file using the bash control-line
#!/bin/bash repeat -n "Input a number: " read number case $number in fifty) repeat "50!!" ;; 100) echo "Double fifty!!" ;; *) echo "Neither 100 nor 200" ;; esac
Execute the file with the fustigate control-line
bash switch_construct.sh
34. Concatenating strings
With its advanced comfort-ability, fustigate allows piece of cake implementation of concatenating cord. This has been simplified by the example beneath. For demonstration purposes, create a file named 'concatenating_strings.sh' and run the file in the bash command line. You lot volition become an output like to the one below.
#!/bin/fustigate string1="FossLinux" string2="Blogsite" string=$string1$string2 echo "$string is a great resource for Linux users to find relevant tutorials."
Execute the file with the bash command
bash concatenating_strings
35. Slicing strings
The slicing string refers to the reduction of parts of a string. Different many programming languages that offer truncation of strings, bash doesn't provide this feature. Beneath is an example to make you get a glimpse of what nosotros are talking near. Beginning, create a file named 'slicing_strings.sh'. Thereafter, execute the created slicing file using the bash control line.
#!/bin/fustigate Str="Study smart commands with fosslinux" subStr=${Str:0:20} echo $subStr The output in the script above should be 'Study Smart commands.' The expansion in parameter takes the formula {VAR_NAME: Southward: L). in this formula, Southward shows the starting position, whereas L denotes the length.
bash slicing_strings.sh
Conclusion
The article has covered 35 bash script examples giving the user a diverse learning range. If you take been looking for an accommodating article with fustigate script examples, this should exist your ultimate choice.
Source: https://www.fosslinux.com/46250/35-bash-script-examples.htm
0 Response to "Linux Bash Script That Reads Csv Files"
Post a Comment