In this article, we are going to learn how to execute a shell script in Linux server.
Create Shell on Server & Run
We can easily create and run a shell script from SSH. Now we will create a shell script which will show the current date. Let’s see the procedure:
1. Create a new file called date.sh. We can make the file by using
sudo nano date.sh command.
2. Add this code:
#!/bin/bash # My first shell script echo "Today is $(date)"
3. Make the shell script executable by hitting this command:
chmod +x date.sh
Our shell is ready to run. Let’s run by this command:
Upload Shell on Server & Run
We have created and run a shell script from the server. Now we will upload a shell to the server and then will run.
Create a file called
date.sh using any text editor (Notepad, Sublime etc.). Then copy-paste the previous shell script and save the file.
After saving to local, upload it to the server using FTP. After doing this, let’s make shell script executable:
chmod +x date.sh
Now try to run the file:
If it works, then okay. But if it doesn’t work, you have to do an extra thing. You can get an error like this:
/bin/bash^M: bad interpreter: No such file or directory
To solve this error, we can follow two methods.
Run this command to fix the error and make a correct shell file:
cat date.sh | tr -d '\r' > date.sh.new
You will see a file called date.sh.new. Delete the date.sh and rename the date.sh.new to date.sh.
Now try to run the script. It should work.
sudo yum -y install dos2unix
Then run this command to convert the file to Unix format:
sudo dos2unix date.sh
Now run the script. It should run.We are done. Thanks for reading. 🙂