Jonasyou
Jonasyou

Reputation: 165

How to run a script shell in google Colab?

I want to run a script shell in colab, i used "!" and also i tried "%%shell" enter image description here

Upvotes: 5

Views: 20012

Answers (3)

Ankeit Taksh
Ankeit Taksh

Reputation: 166

in Colab

!chmod u+x test.sh
!./test.sh

Above is what you need to do.

!test.sh looks for command so it will never work as yours is local script. if you need it as command move it to $PATH directory

Upvotes: 0

Bob Smith
Bob Smith

Reputation: 38619

Either %%shell or ! should work. I suspect your shell script isn't in your current working directory.

You can check the contents of your current directory by running %ls

Here's a complete example of running a shell script: https://colab.research.google.com/drive/1i5lHPcsmcgeoFEGg0Dfwjhblsm2iMExP

enter image description here

Upvotes: 7

alkasm
alkasm

Reputation: 23042

If you're in a shell, you don't just call a .sh file---you should get the same error in your own terminal. Your shell isn't looking in the current directory for shell commands, so you need to add some path context to your script to let shell know it's an actual runnable program, usually via adding a dot before your script, e.g., use

$ . testAllLatin.sh

instead of

$ testAllLatin.sh

Check What's the meaning of a dot before a command in shell? on the Unix Stack Exchange site. The top answer summarizes:

A dot in that context means to "source" the contents of that file into the current shell. With source itself being a shell builtin command. And source and the dot operator being synonyms.


As far as Colab and Notebooks go, the %%shell magic runs the entire cell as a command in a shell. So you should simply be able to use the following in a cell:

%%shell
. path/to/testAllLatin.sh

The bang instead runs just that single line in shell, so you can have Python interspersed if you want. So you could, in a cell, do something like this:

print('this is Python stuff', 5+10)
!. path/to/testAllLatin.sh
print('is it all latin?')

Probably best to keep the shell cells separate, anyways.

Upvotes: 5

Related Questions