Category: Automation and scripts
-
Bash for loop
Below code will print 0 to 100 in bash shell
for ((i = 0 ; i < 100 ; i++)); do echo "$i" doneRanges for for loop
for i in {1..5}; do echo "Welcome to my blog $i" done Expected result Welcome to my blog 1 Welcome to my blog 2 Welcome to my blog 3 Welcome to my blog 4 Welcome to my blog 5With step size of 5
for i in {5..50..5}; do echo "Welcome to my blog $i" done Expected result Welcome to my blog 5 Welcome to my blog 10 Welcome to my blog 15 Welcome to my blog 20 Welcome to my blog 25 Welcome to my blog 30 Welcome to my blog 35 Welcome to my blog 40 Welcome to my blog 45 Welcome to my blog 50Reading lines from a file (file created with few line)
lab01> while read -r line; do echo “$line”; done <file.txt
Expected output from file
apple
orange
toy
car
bus
autoWhile loop executing every 30 sec with sleep command
lab01> while true; do ps -ef | grep 'ssh';sleep 30;doneListing files in a directory
for file in *; do echo $file; done -
Bash shell environment variable
There are several environment variables in bash shell among them few are listed below
echo $PWD ———This will print the current directory
echo $SHELL ——-This will print the shell details
echo $PS1 —-Print the Prompt
echo $PATH —This will print the search path
We can set these environmental variable in the shell using below commands.
export PS1=’lab01> ‘ –This will set the prompt as lab01>
-
My first bash script
What is BASH shell?
Bash is built in shell in most of the Linux operating systems. Its the shell that directly interact with the operating system and executes the commands. Let us write as basic bash shell script that will print a hello message.
#!/bin/bash echo " This is my first bash script"save the code in a file name as script01.sh and execute on the Linux shell. The out put will be as below show:
lab01> bash script01.sh
This is my first bash script