Friday, May 3, 2024
181
rated 0 times [  181] [ 0]  / answers: 1 / hits: 786460  / 3 Years ago, fri, may 7, 2021, 11:41:54

In Windows I can write a file containing commands for cmd (usually .cmd or .bat files). When I click on those files it will open cmd.exe and run them commands the file contains.



How would I do this in Ubuntu?



I'm sure this is a duplicate, but I can't find my answer.

Its similar to these questions, but they don't answer the question:



Store frequently used terminal commands in a file



CMD.exe Emulator in Ubuntu to run .cmd/.bat file


More From » command-line

 Answers
4

There are two methods.



First, the most common is to write a file, make sure the first line is



#!/bin/bash


Then save the file. Next mark it executable using chmod +x file



Then when you click (or run the file from the terminal) the commands will be executed. By convention these files usually have no extension, however you can make them end in .sh or any other way.



A few notes:




  • Any (and I mean any) file can be executed in Linux provided the first line is a path to the program that should interpret the file. Common examples include /bin/python, /bin/sh, /bin/dash, but even odd ball things work like /bin/mysql

  • Bash is a full language. It is vastly more complex than cmd.exe in windows. It has a strong programming language that supports functions, loops, conditionals, string operations, etc.

  • These documents may help if you run into problems.

  • If you do not wish to make the file executable then you can run it by passing it as an argument to bash: bash file/to/run.sh



A Simple Bash Example



#!/bin/bash  
echo "This is a shell script"
ls -lah
echo "I am done running ls"
SOMEVAR='text stuff'
echo "$SOMEVAR"





The second method is to record commands using script. Run script then just do stuff. When you are done doing stuff type exit and script will generate a file for you with all the "stuff" you did. This is less used but works quite well for making things like macros. man script for more info.


[#33955] Saturday, May 8, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ightrushi

Total Points: 129
Total Questions: 125
Total Answers: 127

Location: French Southern and Antarctic Lands
Member since Fri, Jan 6, 2023
1 Year ago
;