Creating and Running Shell Scripts
To create a shell script, simply put bash commands into a file as you would type them. For example, you could put these lines into a file called myscript:
echo "Here are your files:" ls
When you run the script, its commands will run in order:
Here are your files: file1.txt file2.pdf
There are several ways to run a shell script:
- Prepend
#!/bin/bashand make the file executable This is the most common way to run scripts. Add the following line to the top of the script file:
#!/bin/bash
It must be the first line of the file, left-justified. The result in our example looks like this:
#!/bin/bash echo "Here are your files:" ls
Then make the file executable:
➜
chmod +x myscriptMove it into a directory in your search path. Then run it like any other command:
➜
myscriptAlternatively, run the script from your current directory by prepending “./” (indicating the current directory) so the shell finds the script:
➜
./myscriptThe current directory is generally not in your search path for security reasons. You wouldn’t want a local script named, say, “ls” to override the real
lscommand unexpectedly.- Pass to bash
You can run bash directly as a command. It will interpret its argument as the name of a script and run it:
➜
bash myscript- Run in current shell with “.” or
source The preceding methods run your script as an independent entity that has no effect on your current shell.[34] If you want your script to make changes to your current shell (setting variables, changing directory, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access