Getting started with Shell Scripts
Shell script is a collection of Linux commands saved together in a file and executed one after another.
Check out some useful commands you need to know. Below is a simple shell script that resets the previous terminal screen and prints “Hello World”.
Start your Linux terminal or guake terminal and type the command nano hello.sh
Type the following commands in the nano editor.
1 2 3 |
#!/bin/bash reset echo "Hello World" |
Press Ctrl+x to return, then press y to save and exit.
#!/bin/bash – A script may specify #!/bin/bash on the first line, meaning that the script should always be run with bash, rather than another shell.
reset – Resets the previous commands.
echo – Displays the output.
Next go to the path where you have kept the bash file. Mine is in Documents.
1 2 |
ubuntu@ubuntu:~$ cd Documents/ ubuntu@ubuntu:~/Documents$ |
Type ll to view the files in Documents folder along with their permissions.
1 2 3 4 5 |
ubuntu@ubuntu:~/Documents$ ll total 12 drwxr-xr-x 2 ubuntu ubuntu 4096 Jun 17 10:45 ./ drwxr-xr-x 52 ubuntu ubuntu 4096 Jun 17 10:22 ../ -rw-rw-r-- 1 ubuntu ubuntu 33 Jun 17 10:44 hello.sh |
The bash file needs executable permission which is not given in this case. So give them executable permissions.
1 2 3 4 5 6 |
ubuntu@ubuntu:~/Documents$ sudo chmod a+x hello.sh ubuntu@ubuntu:~/Documents$ ll total 12 drwxr-xr-x 2 ubuntu ubuntu 4096 Jun 17 10:45 ./ drwxr-xr-x 52 ubuntu ubuntu 4096 Jun 17 10:22 ../ -rwxrwxr-x 1 ubuntu ubuntu 33 Jun 17 10:44 hello.sh* |
sudo – It is root user. You can avoid it if you are logged in as root user.
chmod – Change the file permissions.
a+x – All user groups should have rights to execute the file. If you don’t want others to access it then you can change it.
1 |
ubuntu@ubuntu:~/Documents$ sudo chmod +x hello.sh |
Now you can execute the script using ./{filename} and prints the output.
1 2 |
ubuntu@ubuntu:~/Documents$ ./hello.sh Hello World |