Basics of Shell Scripting
Create file using below commands
touch myfirstscript.sh
open and edit it in vi editor (Insert mode- I)
#!/bin/sh
# This is a comment! echo Hello World # This is a comment, too! |
Try to execute it
# ./myfirstscript.sh
-bash: ./t1.sh: Permission denied
Give execute permission
chmod +x myfirstscript.sh
Sometime we may encounter with below error while executing shell script.
-bash: ./t2.sh: /bin/sh^M: bad interpreter: No such file or directory
Solution:
-bash: ./t2.sh: /bin/sh^M: bad interpreter: No such file or directory
Solution:
Open vi in command mode (ESC)
:set fileformat=unix
Save:x! or :wq!
Example 1:Script( t1.sh)
Command 'ls' and 'pwd' is executed when we execute the scrip t1.sh file
#!/bin/sh
echo list directory
ls
echo Current Directory
pwd
echo Thanks
|
Output:
# ./t1.sh
list directory
myfirstscript.sh t1.sh t2.sh
Current Directory
/ Backup/test
Thanks
|
Example 2:
Script( t2.sh) (use of variable)
#!/bin/sh
echo what is your name?
read name
echo Great, $name
echo Welcome to our community!!
|
Execute : ./t2.sh
Output:
what is your name?
Devyan Great, Devyan Welcome to our community!! |
Example 3:
Search any file by the name in the directory:
The syntax to store the command output into a variable is
var=$(command).
Files must be present in the location:
A1_test1_abc.txt will move to A1 folder
A2_test2_abc.txt will move to A2 folder
(example3.sh)
#!/bin/sh
# This is a comment!
echo "Provide filename to be
search"
read name
echo "Searching your file,
$name"
find . -type f -name
"$name*"
|
Output:
[root@ test]# ./example3.sh
Provide filename to be search
A1
Searching your file, A1
./A1_test1_abc.txt
|
Example 4:
Move file to some other folder by reading their prefix name
#!/bin/sh
find /TEST/incoming/finished -name "*" -mtime +7 -exec mv {} /TEST/incoming/finished_backup/ \;
Script to fetch http reponse code
#!/bin/sh
url=$1
curl -sL $url -w "%{http_code} %{url_effective}\\n" "URL" -o /dev/null
./testurl https://unix.stackexchange.com
#!/bin/sh
url=$1
curl -sL $url -w "%{http_code} %{url_effective}\\n" "URL" -o /dev/null
./testurl https://unix.stackexchange.com



0 comments:
Post a Comment