what is bash scripting used for

what is bash scripting used for

Bash scripts can be utilized for varied functions, comparable to executing a shell command, operating a number of instructions collectively, customizing administrative duties, performing process automation and many others. So information of bash programming fundamentals is necessary for each Linux consumer. This text will aid you to get the essential concept on bash programming. Many of the frequent operations of bash scripting are defined with quite simple examples right here.

The next subjects of bash programming are coated on this article.

  1. Whats up World
  2. Echo Command
  3. Feedback
  4. Multi-line remark
  5. Whereas Loop
  6. For Loop
  7. Get Person Enter
  8. If assertion
  9. And Situation if assertion
  10. Or Situation if assertion
  11. Else if and else situation
  12. Case Situation
  13. Get Arguments from Command Line
  14. Get arguments from command line with names
  15. Mix two strings in a variable
  16. Get Substring of Strings
  17. Add 2 numbers right into a variable
  18. Create a Perform
  19. Use Perform Parameters
  20. Move Return Worth from Script
  21. Make listing
  22. Make listing by checking existence
  23. Learn a file
  24. Delete a File
  25. Append to file
  26. Check if File Exists
  27. Ship E-mail Instance
  28. Get Parse Present Date
  29. Wait Command
  30. Sleep Command

Create and Execute First BASH Program:

You may run bash script from the terminal or by executing any bash file. Run the next command from the terminal to execute a quite simple bash assertion. The output of the command will probably be ‘Whats up World’.

You’re reading: what is bash scripting used for

$ echo “Whats up World”

Open any editor to create a bash file. Right here, nano editor is used to create the file and filename is ready as ‘First.sh’

$ nano newurbanhabitat.com

Add the next bash script to the file and save the file.

#!/bin/bash echo “Whats up World”

You may run bash file by two methods. A technique is through the use of bash command and one other is by setting execute permission to bash file and run the file. Each methods are proven right here.

$ bash newurbanhabitat.com

Or,

$ chmod a+x newurbanhabitat.com $ ./newurbanhabitat.com

Go to prime

Use of echo command:

You should use echo command with varied choices. Some helpful choices are talked about within the following instance. If you use ‘echo’ command with none possibility then a newline is added by default. ‘-n’ possibility is used to print any textual content with out new line and ‘-e’ possibility is used to take away backslash characters from the output. Create a brand new bash file with a reputation, ‘echo_example.sh’ and add the next script.

#!/bin/bash echo “Printing textual content with newline” echo -n “Printing textual content with out newline” echo -e “nRemoving t backslash t charactersn”

Run the file with bash command.

$ bash newurbanhabitat.com

Go to prime

Use of remark:

‘#’ image is used so as to add single line remark in bash script. Create a brand new file named ‘comment_example.sh’ and add the next script with single line remark.

#!/bin/bash # Add two numeric worth ((sum=25+35)) #Print the end result echo $sum

Run the file with bash command.

$ bash newurbanhabitat.com

Go to prime

Use of Multi-line remark:

You should use multi line remark in bash in varied methods. A easy approach is proven within the following instance. Create a brand new bash named, ‘multiline-comment.sh’ and add the next script. Right here, ‘:’ and symbols are used so as to add multiline remark in bash script. This following script will calculate the sq. of 5.

#!/bin/bash : ‘ The next script calculates the sq. worth of the quantity, 5. ‘ ((space=5*5)) echo $space

Run the file with bash command.

$ bash newurbanhabitat.com

You may test the next hyperlink to know extra about the usage of bash remark.

Go to prime

Utilizing Whereas Loop:

Create a bash file with the identify, ‘while_example.sh’, to know the usage of whereas loop. Within the instance, whereas loop will iterate for 5 instances. The worth of depend variable will increment by 1 in every step. When the worth of depend variable will 5 then the whereas loop will terminate.

#!/bin/bash legitimate=true depend=1 whereas [ $valid ] do echo $depend if [ $count -eq 5 ]; then break fi ((depend++)) performed

Run the file with bash command.

$ bash newurbanhabitat.com

You may test the next hyperlink to know extra about the usage of whereas loop.

Go to prime

Utilizing For Loop:

The essential for loop declaration is proven within the following instance. Create a file named ‘for_example.sh’ and add the next script utilizing for loop. Right here, for loop will iterate for 10 instances and print all values of the variable, counter in single line.

#!/bin/bash for (( counter=10; counter>0; counter- )) do echo -n “$counter ” performed printf “n”

Run the file with bash command.

$ bash newurbanhabitat.com

You should use for loop for various functions and methods in your bash script. You may test the next hyperlink to know extra about the usage of for loop.

Go to prime

Get Person Enter:

learn’ command is used to take enter from consumer in bash. Create a file named ‘user_input.sh’ and add the next script for taking enter from the consumer. Right here, one string worth will probably be taken from the consumer and show the worth by combining different string worth.

#!/bin/bash echo “Enter Your Identify” learn identify echo “Welcome $identify to LinuxHint”

Run the file with bash command.

$ bash newurbanhabitat.com

You may test the next hyperlink to know extra about the usage of consumer enter.

Go to prime

Utilizing if assertion:

You should use if situation with single or a number of circumstances. Beginning and ending block of this assertion is outline by ‘if’ and ‘fi’. Create a file named ‘simple_if.sh’ with the next script to know the use if assertion in bash. Right here, 10 is assigned to the variable, n. if the worth of $n is lower than 10 then the output will probably be “It’s a one digit quantity”, in any other case the output will probably be “It’s a two digit quantity”. For comparability, ‘-lt’ is used right here. For comparability, you too can use ‘-eq’ for equality, ‘-ne’ for not equality and ‘-gt’ for larger than in bash script.

#!/bin/bash n=10 if [ $n -lt 10 ]; then echo “It’s a one digit quantity” else echo “It’s a two digit quantity” fi

Run the file with bash command.

$ bash newurbanhabitat.com

Go to prime

Utilizing if assertion with AND logic:

Various kinds of logical circumstances can be utilized in if assertion with two or extra circumstances. How one can outline a number of circumstances in if assertion utilizing AND logic is proven within the following instance. ‘&&’ is used to use AND logic of if assertion. Create a file named ‘if_with_AND.sh’ to test the next code. Right here, the worth of username and password variables will probably be taken from the consumer and in contrast with ‘admin’ and ‘secret’. If each values match then the output will probably be “legitimate consumer”, in any other case the output will probably be “invalid consumer”.

!/bin/bash echo “Enter username” learn username echo “Enter password” learn password if [[ ( $username == “admin” && $password == “secret” ) ]]; then echo “legitimate consumer” else echo “invalid consumer” fi

Run the file with bash command.

$ bash newurbanhabitat.com

Go to prime

Utilizing if assertion with OR logic:

Read more: what is the difference between city skylines and city skylines deluxe

||’ is used to outline OR logic in if situation. Create a file named ‘if_with_OR.sh’ with the next code to test the usage of OR logic of if assertion. Right here, the worth of n will probably be taken from the consumer. If the worth is the same as 15 or 45 then the output will probably be “You gained the sport”, in any other case the output will probably be “You misplaced the sport”.

#!/bin/bash echo “Enter any quantity” learn n if [[ ( $n -eq 15 || $n -eq 45 ) ]] then echo “You gained the sport” else echo “You misplaced the sport” fi

Run the file with bash command.

$ bash newurbanhabitat.com

Go to prime

Utilizing else if assertion:

Using else if situation is little totally different in bash than different programming language. ‘elif’ is used to outline else if situation in bash. Create a file named, ‘elseif_example.sh’ and add the next script to test how else if is outlined in bash script.

#!/bin/bash echo “Enter your fortunate quantity” learn n if [ $n -eq 101 ]; then echo “You bought 1st prize” elif [ $n -eq 510 ]; then echo “You bought 2nd prize” elif [ $n -eq 999 ]; then echo “You bought third prize” else echo “Sorry, strive for the subsequent time” fi

Run the file with bash command.

$ bash newurbanhabitat.com

Go to prime

Utilizing Case Assertion:

Case assertion is used as the choice of if-elseif-else assertion. The beginning and ending block of this assertion is outlined by ‘case’ and ‘esac’. Create a brand new file named, ‘case_example.sh’ and add the next script. The output of the next script will probably be identical to the earlier else if instance.

#!/bin/bash echo “Enter your fortunate quantity” learn n case $n in 101) echo echo “You bought 1st prize” ;; 510) echo “You bought 2nd prize” ;; 999) echo “You bought third prize” ;; *) echo “Sorry, strive for the subsequent time” ;; esac

Run the file with bash command.

$ bash newurbanhabitat.com

Go to prime

Get Arguments from Command Line:

Bash script can learn enter from command line argument like different programming language. For instance, $1 and $2 variable are used to learn first and second command line arguments. Create a file named “command_line.sh” and add the next script. Two argument values learn by the next script and prints the whole variety of arguments and the argument values as output.

#!/bin/bash echo “Complete arguments : $#” echo “1st Argument = $1” echo “2nd argument = $2”

Run the file with bash command.

$ bash newurbanhabitat.com Linux Trace

You may test the next hyperlink to know extra about the usage of command line argument.

Go to prime

Get arguments from command line with names:

How one can learn command line arguments with names is proven within the following script. Create a file named, ‘command_line_names.sh’ and add the next code. Right here, two arguments, X and Y are learn by this script and print the sum of X and Y.

#!/bin/bash for arg in “[email protected]” do index=$(echo $arg | reduce -f1 -d=) val=$(echo $arg | reduce -f2 -d=) case $index in X) x=$val;; Y) y=$val;; *) esac performed ((end result=x+y)) echo “X+Y=$end result”

Run the file with bash command and with two command line arguments.

$ bash command_line_names X=45 Y=30

Go to prime

Mix String variables:

You may simply mix string variables in bash. Create a file named “string_combine.sh” and add the next script to test how one can mix string variables in bash by putting variables collectively or utilizing ‘+’ operator.

#!/bin/bash string1=”Linux” string2=”Trace” echo “$string1$string2″ string3=$string1+$string2 string3+=” is an effective tutorial weblog website” echo $string3

Run the file with bash command.

$ bash newurbanhabitat.com

Go to prime

Get substring of String:

Like different programming language, bash has no built-in perform to chop worth from any string information. However you are able to do the duty of substring in one other approach in bash that’s proven within the following script. To check the script, create a file named ‘substring_example.sh’ with the next code. Right here, the worth, 6 signifies the place to begin from the place the substring will begin and 5 signifies the size of the substring.

#!/bin/bash Str=”Be taught Linux from LinuxHint” subStr=${Str:6:5} echo $subStr

Run the file with bash command.

$ bash newurbanhabitat.com

Go to prime

Add Two Numbers:

You are able to do the arithmetical operations in bash in numerous methods. How one can add two integer numbers in bash utilizing double brackets is proven within the following script. Create a file named ‘add_numbers.sh’ with the next code. Two integer values will probably be taken from the consumer and printed the results of addition.

#!/bin/bash echo “Enter first quantity” learn x echo “Enter second quantity” learn y (( sum=x+y )) echo “The results of addition=$sum”

Run the file with bash command.

$ bash newurbanhabitat.com

You may test the next hyperlink to know extra about bash arithmetic.

Go to prime

Create Perform:

How one can create a easy perform and name the perform is proven within the following script. Create a file named ‘function_example.sh’ and add the next code. You may name any perform by identify solely with out utilizing any bracket in bash script.

#!/bin/bash perform F1() { echo ‘I like bash programming’ } F1

Run the file with bash command.

$ bash newurbanhabitat.com

Go to prime

Create perform with Parameters:

Bash can’t declare perform parameter or arguments on the time of perform declaration. However you should utilize parameters in perform through the use of different variable. If two values are handed on the time of perform calling then $1 and $2 variable are used for studying the values. Create a file named ‘perform|_parameter.sh’ and add the next code. Right here, the perform, ‘Rectangle_Area’ will calculate the world of a rectangle based mostly on the parameter values.

#!/bin/bash Rectangle_Area() { space=$(($1 * $2)) echo “Space is : $space” } Rectangle_Area 10 20

Run the file with bash command.

$ bash newurbanhabitat.com

Go to prime

Move Return Worth from Perform:

Bash perform can go each numeric and string values. How one can go a string worth from the perform is proven within the following instance. Create a file named, ‘function_return.sh’ and add the next code. The perform, greeting() returns a string worth into the variable, val which prints later by combining with different string.

#!/bin/bash perform greeting() { str=”Whats up, $identify” echo $str } echo “Enter your identify” learn identify val=$(greeting) echo “Return worth of the perform is $val”

Run the file with bash command.

$ bash newurbanhabitat.com

You may test the next hyperlink to know extra about the usage of bash perform.

Go to prime

Make Listing:

Read more: what is the difference between christmas and hanukkah

Bash makes use of ‘mkdir’ command to create a brand new listing. Create a file named ‘make_directory.sh’ and add the next code to take a brand new listing identify from the consumer. If the listing identify will not be exist within the present location then it can create the listing, in any other case this system will show error.

#!/bin/bash echo “Enter listing identify” learn newdir `mkdir $newdir`

Run the file with bash command.

$ bash newurbanhabitat.com

Go to prime

Make listing by checking existence:

If you wish to test the existence of listing within the present location earlier than executing the ‘mkdir’ command then you should utilize the next code. ‘-d’ possibility is used to check a specific listing is exist or not. Create a file named, ‘directory_exist.sh’ and add the next code to create a listing by checking existence.

#!/bin/bash echo “Enter listing identify” learn ndir if [ -d “$ndir” ] then echo “Listing exist” else `mkdir $ndir` echo “Listing created” fi

Run the file with bash command.

$ bash newurbanhabitat.com

You may test the next hyperlink to know extra about listing creation.

Go to prime

Learn a File:

You may learn any file line by line in bash through the use of loop. Create a file named, ‘read_file.sh’ and add the next code to learn an current file named, ‘ebook.txt’.

#!/bin/bash file=’ebook.txt’ whereas learn line; do echo $line performed < $file

Run the file with bash command.

$ bash newurbanhabitat.com

Run the next command to test the unique content material of ‘ebook.txt’ file.

$ cat newurbanhabitat.com

You may test the next hyperlink to know the alternative ways to learn file.

Go to prime

Delete a File:

rm’ command is utilized in bash to take away any file. Create a file named ‘delete_file.sh’ with the next code to take the filename from the consumer and take away. Right here, ‘-i’ possibility is used to get permission from the consumer earlier than eradicating the file.

#!/bin/bash echo “Enter filename to take away” learn fn rm -i $fn

Run the file with bash command.

$ ls $ bash newurbanhabitat.com $ ls

Go to prime

Append to File:

New information might be added into any current file through the use of ‘>>’ operator in bash. Create a file named ‘append_file.sh’ and add the next code so as to add new content material on the finish of the file. Right here, ‘Studying Laravel 5’ will probably be added on the of ‘ebook.txt’ file after executing the script.

#!/bin/bash echo “Earlier than appending the file” cat newurbanhabitat.com echo “Studying Laravel 5”>> newurbanhabitat.com echo “After appending the file” cat newurbanhabitat.com

Run the file with bash command.

$ bash newurbanhabitat.com

Go to prime

Check if File Exist:

You may test the existence of file in bash through the use of ‘-e’ or ‘-f’ possibility. ‘-f’ possibility is used within the following script to check the file existence. Create a file named, ‘file_exist.sh’ and add the next code. Right here, the filename will go from the command line.

#!/bin/bash filename=$1 if [ -f “$filename” ]; then echo “File exists” else echo “File doesn’t exist” fi

Run the next instructions to test the existence of the file. Right here, newurbanhabitat.com file exists and newurbanhabitat.com will not be exist within the present location.

$ ls $ bash newurbanhabitat.com newurbanhabitat.com $ bash newurbanhabitat.com newurbanhabitat.com

Go to prime

Ship E-mail:

You may ship electronic mail through the use of ‘mail’ or ‘sendmail’ command. Earlier than utilizing these instructions, it’s important to set up all mandatory packages. Create a file named, ‘mail_example.sh’ and add the next code to ship the e-mail.

#!/bin/bash Recipient=”admin@instance.com” Topic=”Greeting” Message=”Welcome to our website” `mail -s $Topic $Recipient <<< $Message`

Run the file with bash command.

$ bash newurbanhabitat.com

Go to prime

Get Parse Present Date:

You will get the present system date and time worth utilizing `date` command. Each a part of date and time worth might be parsed utilizing ‘Y’, ‘m’, ‘d’, ‘H’, ‘M’ and ‘S’. Create a brand new file named ‘date_parse.sh’ and add the next code to separate day, month, yr, hour, minute and second values.

#!/bin/bash Yr=`date +%Y` Month=`date +%m` Day=`date +%d` Hour=`date +%H` Minute=`date +%M` Second=`date +%S` echo `date` echo “Present Date is: $Day-$Month-$Yr” echo “Present Time is: $Hour:$Minute:$Second”

Run the file with bash command.

$ bash newurbanhabitat.com

Go to prime

Wait Command:

wait is a built-in command of Linux that waits for finishing any operating course of. wait command is used with a specific course of id or job id. If no course of id or job id is given with wait command then it can look forward to all present baby processes to finish and returns exit standing. Create a file named ‘wait_example.sh’ and add the next script.

#!/bin/bash echo “Wait command” & process_id=$! wait $process_id echo “Exited with standing $?”

Run the file with bash command.

$ bash newurbanhabitat.com

You may test the next hyperlink to know extra about wait command.

Wait Command in Linux

Go to prime

Sleep Command:

If you need to pause the execution of any command for particular time period then you should utilize sleep command. You may set the delay quantity by seconds (s), minutes (m), hours (h) and days (d). Create a file named ‘sleep_example.sh’ and add the next script. This script will wait for five seconds after operating.

#!/bin/bash echo “Wait for five seconds” sleep 5 echo “Accomplished”

Run the file with bash command.

$ bash newurbanhabitat.com

You may test the next hyperlink to know extra about sleep command.

Go to prime

Hope, after studying this text you’ve got a fundamental idea on bash scripting language and it is possible for you to to use them based mostly in your necessities.

Read: what is bobby jones wife name