Unix Shell Scripts   «Prev  Next»
Lesson 9 Running the script
Objective Run a script from a command line in Unix

Running a Shell Script from the Command Line

Once you have created a shell script and given it execute permission, you can run it like any other program. The key detail is that Unix only finds programs automatically if they are located in a directory listed in your PATH environment variable. Your training scripts (like welcome) usually live in your home directory, so you must run them using an explicit path.

Run a Script in Your Current Directory

If your script is in your current working directory, typing its filename by itself usually fails:
% welcome
welcome: not found
This happens because the current directory (.) is normally not included in PATH for security reasons.

To run a script that is in the current directory, prefix it with ./:
% ./welcome
If execute permission is set, the script runs immediately using the interpreter specified on the first line (the shebang), such as #!/bin/sh.

Alternative: Run the Script with an Interpreter

Another common method is to call the interpreter directly and pass the script as an argument:
% sh ./welcome
This is useful when:
  • You want to ensure a specific shell is used (for example sh vs bash).
  • The script is not executable yet (you can still run it with sh script).
  • You want to debug execution (for example, some shells support flags like -x to trace commands).
In practice, if your script starts with #!/bin/sh and has execute permission, using ./welcome is the cleanest workflow.

Putting Scripts Somewhere Unix Can Find Them

If you want to run your scripts without typing ./, place them in a directory that is already in your PATH, or create a personal scripts directory such as $HOME/bin and add it to your PATH.

Best practice is to avoid adding the current directory (.) to PATH, because it can allow unintended programs to run if a malicious or accidental filename matches a command you type.

Common Errors and Fixes

  • Permission denied: add execute permission (for example chmod u+x welcome).
  • not found: run with ./welcome or provide the full/relative path.
  • bad interpreter: the shebang path is wrong or the file has Windows CRLF line endings—convert to Unix LF.

Shell Script File Permissions - Quiz

Click the Quiz link below to test your knowledge of file permissions and script execution.
Shell Script File Permissions - Quiz
The next lesson wraps up what you have learned in this module.

SEMrush Software 9 SEMrush Banner 9