Skip to content

Rezaid

Home » Blog » How to run a bash script​

How to run a bash script​

    How to run a bash script

    With software development, system administration and even recreational computing, the capability to automate repetitive processes is the superpower. The secret of this power on Linux, macOS and even on Windows (using WSL or Git Bash) is frequently the simple Bash script. A script written using the Bash language is just a plain text file consisting of a series of commands which may be executed by the Bash shell. But when you are at the command line and new to it you do not always know how to run that script. This guide will take you through the different methods and why they work and prepare you to execute any script that you come across. Learn more about automated testing and how scripting fits into modern QA processes.

    Requirements: To test a simple script to write.

    Requirements To test a simple script to write

    You have to have one before you can run a script. To demonstrate, we’ll write a simple and harmless script. Open a terminal and open a text editor such as nano:

     

    bash

    nano hello_world.sh

    These lines are to be typed in the editor. The opening line is unique and vital, as we will see in the future.

     

    bash

    #!/bin/bash

    # This is a comment. It won’t be executed.

    echo “Hello, World!”

    echo: time and date are: $(date).

    Write and quit the editor (in nano, Ctrl+X, then Y for yes, then Enter).

     

    Congratulations! The script file is now created: hello world.sh. But when you attempt to run it right away, typing its name, you are likely to get an error:

     

    Bash

    $ hello_world.sh

    Hello, world.sh: command not found.

    This is the initial big obstacle for newcomers. The system does not simply run any file that you type. You must inform them of how to perform it. Let us consider the right methods.

    Method 1: How to make the Script executable (The Standard Way)

    How to make the Script executable

    This is the most appropriate and standard way of executing scripts that you intend to use on a regular basis. It involves two steps.

    Step 1: Select the Execute Permission.

    Unix-like systems feature files with permissions that allow specifying who is allowed to read write to or execute a file. The default permission of a new text file is not the execute (x) permission. We give it with the change mode (chmod) command.

    bash

    chmod +x hello_world.sh

    chmod: The command.

    +x: Add execute permission to the user and group and also to others (a shorthand of a+x).

    Hello world.sh: The target file.

    The permissions also could be checked by running ls -l. You can view the x in the permission string (e.g. -rwxr-xr-x). Explore some essential automation tools for testers and developers.

    Step 2: Execute the Script

    At this point the file is ready to run. But security reasons keep the shell in your current directory and unless it is explicitly instructed to the contrary, it does not search there. You have two options:

    Option A: Specify the Path (./)

    The safest and the advisable method is to give the route to the script. The/ is an abbreviation of in the current directory.

    bash

    ./hello_world.sh

    Output:

    text

    Hello, World!

    The system date and time are: Sun Sep 8 10:30:00 UTC 2024.

    Option B: relocate to a Script Directory on your $PATH.

    To have your script run like any other command, e.g. by simply typing hello-world.sh, anywhere, you can move it to a directory in the system PATH, e.g., /usr/local/bin/.

    bash

    mv that script (must use sudo with system directories).

    Sudo mv hello world.sh to /usr/local/bin/

    Now it can be executed out of any directory.

    hello_world.sh

    This is ideal with well-tried scripts used on a system-wide basis. See how scripting supports developer workflows across languages like Python and Bash.

    Step 2: Execute the Script

    There are times when you do not wish the script to execute a new shell process. Rather you need it to operate in your existing shell. It is accomplished through sourcing the script.

    The source command can be used, or the dot (.) operator (equivalent):

    bash

    Both these commands are identical.

    source hello_world.sh

    ./hello_world.sh

    Why would you do this?

    The major dissimilarity lies in the way variables and changes in the environment are processed.

    Normal execution (./script sh): The script executes in a subshell. Any variables it establishes or any directory changes (cd) it makes are lost after the script has been executed. They are not taken into your current terminal session.

    Sourcing (source script.sh): The commands in the script are run like the commands typed in your current shell. Any changes it makes persist.

    Example Use Case: You have a script that initializes a number of environment variables to a development project. You would like such variables to appear on your terminal once the script is run. configure_environment.sh would be sourced.

    For real-world examples, see how data automation works inside specialized software tools.

    Caution: You should not execute any other script without first verifying the authorship of the author since this source would permanently modify your shell environment.

    Method 3: bash invocation.

    You can even avoid the requirement of the execute permission at all by simply using the script as an argument to the bash command itself.

    bash

    bash hello_world.sh

    By so doing, you are directly launching a new Bash shell and telling it to read and run the contents of hello_world.sh. This #!/bin/bash line (so-called shebang) within the script is excluded since you have already stated what interpreter to use.

    It is an excellent way of:

    Test a script very quickly without having to muck around with chmod.

    Execution of a script compiled to run on another shell (e.g. one may execute sh script.sh to run it on the simpler sh interpreter).

    You can add flags such as -x to make all the calls visible as they are run: debugging.

     

    bash

    bash -x hello_world.sh

    Output:

     

    text

    + echo ‘Hello, World!’

    Hello, World!

    + date

    + date September 8, 2024, 10:30:00

    + time Sun Sep 8 10:30:00 UTC 2024

    The time and date are: Sun Sep 8 10:30:00 UTC 2024.

    The shebang (#!/bin/bash)

    Our initial line of script, #!/bin/bash is known as a shebang (or hashbang). It is magic that makes Methods 1 and 2 work.

    When you just run a file (e.g., ./myscript), the operating system takes a look at this first line to determine what program is to be used to interpret the file. The #! informs the OS that this is a script and the path /bin/bash is the absolute path to the interpreter in this case being the Bash shell.

    This is so potent in that what is written in any interpreted language can be run without problems:

    For Python: #!/usr/bin/env python3

    For Perl: #!/usr/bin/perl

    For Node.js: #!/usr/bin/env node

     

    A typical workaround is to use the trick /usr/bin/env in order to execute the env command to identify the interpreter in the user’s path, which makes the script more portable.

    When the shebang is absent and one tries to run the script directly, the system will normally attempt to run the script in your present shell. This may be fine with simple Bash scripts, but it is not very reliable and is bad practice. Always include a shebang.

    It is possible to troubleshoot Common Permission Errors.

    Access denied: You have not executed chmod +x script.sh. Use this or execute it with a bash script.sh.

     

    Unknown command: You have typed the name of the script but have not given the path. In the same directory use ./script sh.


    No file or directory of this type: You are probably in the discarded files directory. To list files, use ls and to identify where you are, use pwd and then change to the right directory using the command cd. Furthermore, verify the typos in the name.

    Conclusion

    Ancillary skills such as running a Bash script open oopenthe gate to amazing efficiency. To recap: The regular method: chmod +x script.sh and script.sh. To make current shell changes: source script.sh or source.script.sh. To debug or to quickly test: bash script.sh or bash -x script.sh Also bear in mind the strength of the shebang (#!/bin/bash) in order to make your scripts self-contained and portable. These are just some of the easy ways to start and automate simple tasks, and with practice you can use the complete power of the command line to have your computer do the work.



    FAQs

    1. How do I run a Bash script?

    Make it executable and run the script.sh, or execute the bash script.sh.

     

    2. Why do I need chmod +x?

    It authorizes the file to execute as a program.

     

    3. What does “./” mean?

    It directs the shell to search the script in the present folder.

     

    4. What is #!/bin/bash?

    It’s a shebang, which instructs the system to use Bash to execute the script.

     

    5. What is the difference between ./script sh and source script.sh?

    ./ opens a new shell and the source uses the current shell.

     

    6. Is it possible to execute Bash scripts under Windows?

    Yes, in WSL, Git Bash, or Cygwin.

     

    7. Why do I get “command not found”?

    You have either forgotten ./ or are not there.

     

    8. How do I debug a script?

    Bash -x script.sh to view each command as it is being run.