乐闻世界logo
搜索文章和话题

How to run a shell script on a Unix console or Mac terminal?

1个答案

1

To run a shell script on Unix command line or Mac Terminal, follow these steps:

Step 1: Create the Script

First, create a shell script file. This file contains the commands you want to execute. For example, assume your script file is named script.sh; you can create and write the following content using a text editor:

bash
#!/bin/bash echo "Hello, World!"

The #!/bin/bash line is known as a shebang, which specifies the interpreter to use for executing the script. In this example, it uses the bash interpreter.

Step 2: Grant Execute Permissions

By default, newly created scripts may not have execute permissions. You need to grant execute permissions using the following command:

bash
chmod +x script.sh

This command makes the script.sh script executable.

Step 3: Run the Script

After granting execute permissions, you can run the script using any of the following methods:

  • Run directly using absolute or relative path:
    bash
    ./script.sh
    Or if the script is in another directory:
    bash
    /path/to/script.sh
  • Explicitly call using bash command:
    bash
    bash script.sh

Example

Suppose you create a script to clean temporary files. The script content is as follows:

bash
#!/bin/bash # Clean files in /tmp directory rm -rf /tmp/*

Following the above steps, first grant execute permissions to the script, then run it. This will clear all files in the /tmp directory.

Important Notes

  • Ensure the first line of your script correctly specifies the shebang, as it is critical for proper script execution.
  • Before executing scripts that involve file deletion or system changes, make sure to back up important data.
  • Use absolute paths to avoid dependency on the current working directory.

By following these steps, you can successfully run a shell script on Unix command line or Mac Terminal.

2024年8月16日 23:21 回复

你的答案