how to convert a text/plain to text/x.shellscript

2019-05-12 12:44发布

问题:

I am sending a .sh file created from a windows machine to a linux so that I could run it there. The problem is that I keep on getting an error called bad interpreter.But when I program the shell script in the linux machine it runs with no problems even though it has the same code with the one sent from the windows machine. After my ivestigation, I found out that the windows machine .sh script is a text/plain file(using file -bi) and the other one from the linux machine is a text/x.shellscript. Is there a way to convert the text/plain to a text/x.shellscript? thank you

this is the script:

#!/bin/bash

date
sudo apt-get update

I tried a solution by doing another .sh file in a linux box containing only

#!/bin/bash

Then the windows machine only sent a file containing test commands like :

date
hostname

Then I append the file from the windows box to the linux one with

cat windows.sh >> linux.sh

It did not work if I run linux.sh. It says errors like:

./linuxh.sh: line 2 $'date\r':command not found
./linuxh.sh: line 2 $'hostname\r':command not found

However, if I open Linux.sh then save it again without doing anything. It works

回答1:

I'm summarising below the steps you need to take so other users can see easily what needs doing:

Firstly, you need to check your script has the correct path to your interpreter after the "#!" in the very first line. This is should probably be:

#!/bin/bash

or

#!/usr/bin/bash

and you can find which is correct by typing:

which bash 

on your Linux box.

Secondly, you need to make sure that any Windows carriage returns (or "^M") at the ends of the lines are removed before expecting your Linux box to run the script. You can do this with:

dos2unix yourscript

Just for reference, you can easily see weird characters such as TABs or linefeeds or carriage returns in Linux by using:

cat -vet yourfile

or

sed -n l yourfile

Thirdly, you need to make sure your script is executable on Linux, using chmod like this:

chmod +x yourscript

Finally, when you have done all that, you need to either add the directory where the script is located to your PATH variable (and export it) or give the full path to your script like this if your script is in the current directory:

./yourscript

or like this if it is located somewhere else

/some/directory/some/where/yourscript