In this tutorial, we will discuss various ways to run a ZSH script.
What is a ZSH Script?
A ZSH shell script is a text file that contains instructions or commands to be executed by the ZSH shell. The ZSH shell is an extended version of the Bourne Again Shell; thus, most commands and scripts written for bash will work on ZSH.
The ZSH shell provides full programming language features such as variables, control flow, loops, functions, and more.
How to Run a ZSH Script
Once you have your shell script complete and ready to go, you will need to modify its file permissions before executing it, which you can do using the chmod command.
To set the execute permissions for your shell script, use the commands:
You can also use the octal representation to change the permissions as:
Although adding the .sh extension to your shell script is expected, it is not required, and the commands in your shell script will work with or without the .sh extension.
To run your script, you can provide the full file path to the script. For example, if the file is in the Documents folder, you can do:
If your script accepts any arguments, you can pass them just like you would in a normal command.
You can also pass a relative path to your bash script. For example:
Explicitly call ZSH
Although most scripts written for bash will work on ZSH shell and vice versa, you may need to use a specific shell interpreter explicitly.
You can do this by adding a shebang at the document preamble or calling the script using your desired shell.
To use zsh explicitly, add the shebang as:
Before adding the shebang, ensure you have the correct path to the ZSH binary. You can do this using the which command as:
/usr/bin/zsh
To specify the interpreter to use, use the command:
The above syntax will launch your script using the specified shell interpreter.
Conclusion
In this tutorial, we looked at various ways to execute your zsh scripts straight from the terminal. We also discussed how to specify your desired shell interpreter either using the shebang or the command.
If you are interested in shell scripting, check out our other bash scripting tutorials for in-depth guides.
Thank you for reading!