Creating and Running bash and zsh Scripts
Last Updated :
16 Sep, 2024
Creating and running scripts can be a powerful tool for automating tasks and streamlining workflow. Bash and Zsh are two popular shells that can be used to create and run scripts on Linux and macOS systems. Bash, which stands for Bourne-Again Shell, is the default shell on most Linux distributions and macOS. Zsh, or Z shell, is a more feature-rich alternative to Bash that offers improved tab completion and command history among other features.
Here, we will discuss how to create and run scripts using both Bash and Zsh, including basic syntax and examples of common tasks that can be automated with scripts.
Why Use Scripting in Bash and Zsh?
Scripts allow you to execute a series of commands automatically, reducing the need for manual input and minimizing errors. By learning to script in Bash or Zsh, you can automate system maintenance tasks, file management, backups, and other repetitive tasks that would otherwise take up valuable time. Both shells support a wide range of scripting capabilities, including loops, conditional statements, and variables, enabling the automation of complex workflows.
How to Create and Run Scripts in Bash and Zsh
To create a script, you will first need to open a text editor and type in the commands you want the script to execute. It is important to make sure that the script is saved with the '.sh' extension for Bash or '.zsh' extension for Zsh. Once your script is saved, you will need to make it executable by running the command "chmod +x [scriptname]" in the terminal.
To run the script, you can use the terminal command "./[scriptname]". If your script is located in a directory that is not in your system's PATH, you will need to specify the full path to the script when running it. For example, if your script is located in the Documents folder, you would run "./Documents/[scriptname]".
Creating a Bash Script
- Prints the current date and time
- Creates a new directory named "test"
- Changes in the "test" directory
- Creates a new file named "test.txt" and writes the text "Hello, World!" to the file
- Prints the contents of the "test.txt" file
- Changes back to the parent directory
- Deletes the "test" directory
The script contains the explanation of each step with the command explanation.
Step 1. Open a terminal window.
Step 2. Use the nano or vi commands to open a new blank file in a text editor. For example nano myscript.sh.
$ nano myscript.sh
Step 3. Type the bash commands that you want to include in the script. you can see we have written a sample script below.
#!/bin/bash
# This line prints the current date and time
echo "Current date and time: $(date)"
# This line creates a new directory named "test"
mkdir test
# This line changes into the "test" directory
cd test
# This line creates a new file named "test.txt" and writes the text "Hello, World!" to the file
echo "Hello, World!" > test.txt
# This line prints the contents of the "test.txt" file
cat test.txt
# This line changes back to the parent directory
# The 'cd ..' command is used to change to the parent directory (i.e., the directory one level up)
cd ..
# This line deletes the "test" directory
rm -r test
Step 4. Save the file by pressing CTRL + X, then Y, and then Enter.
Save and Exit the Text EditorStep 5. Make the script executable by running the chmod command: 'chmod +x myscript.sh'
$ chmod +x myscript.sh
Step 6. Run the script:
./myscript.sh
And here is an example output of the script:
output of the scriptCurrent date and time: Tue Jan 6 20:23:45 UTC 2023
Hello, World!
Creating a Zsh Script
Step 1: Open a terminal window.
Step 2: Use the nano or vi commands to open a new blank file in a text editor. For example: nano myscript.zsh
Step 3: Type the zsh commands that you want to include in the script.
#!/bin/zsh
# This line sets the variable 'filename' to the first argument passed to the script
filename=$1
# This line prints the hostname of the current system
echo "Hostname: $(hostname)"
# This line creates a subshell and runs the 'ls' command inside it.
# The output of the 'ls' command is then stored in the 'ls_output' variable
ls_output=$(ls)
echo "Output of 'ls' command: $ls_output"
# This line checks if the file specified by the 'filename' variable exists
# and is a regular file (not a directory). If the file exists, it prints the contents
# of the file using the 'cat' command. If the file does not exist, it prints an error message
if [[ -f "$filename" ]]; then
cat "$filename"
else
echo "Error: File not found"
fi
# This line prints the current working directory
echo "Current working directory: $(pwd)"
# This line prints the current user's home directory
echo "Home directory: $HOME"
# This line reads input from the user and stores it in the 'input' variable
echo -n "Enter your name: "
read input
# This line prints the value of the 'input' variable
echo "Your name is: $input"
Step 4: Save the file by pressing 'CTRL + X', then 'Y', and then Enter.
Â
Step 5: Make the script executable by running the chmod command: chmod +x myscript.zsh
$ chmod +x myscript.zsh
Step 6: Run the script by typing its name at the command prompt, followed by any arguments that the script expects: ./myscript.zsh argument1 argument2
./myscript.zsh argument1 argument2
Here is the output of the above zsh script after executing it:
Hostname: myhostname
Output of 'ls' command: test.txt
Hello, World!
Current working directory: /home/user/documents
Home directory: /home/user
Enter your name: John
Your name is: John
Conclusion
Bash and Zsh scripts are powerful tools for automating tasks and streamlining workflow on Linux and macOS systems. Creating scripts is as simple as writing a list of commands in a text editor and saving it with the appropriate file extension. Running the script is as easy as using the command "./[scriptname]" in the terminal.
Both Bash and Zsh offer a variety of features and capabilities, including control structures, loops, and conditional statements, which can be used to automate more complex tasks. With a little bit of practice and experimentation, anyone can learn to create powerful scripts that can save time and effort on a daily basis.
Similar Reads
Bash Scripting - Difference between Zsh and Bash A shell is an environment in which various commands can be executed, it provides an interface between the user and the UNIX system. Basically, a shell is a command-line interpreter which interprets the commands given by the user, it can also read the combination of such commands which is known as a
2 min read
Shell Scripting - Creating a Binary file While working in Linux systems, we have used so many commands on a day-to-day basis. Most of the commands are in the binary format resides under /bin, /sbin, /usr/bin, /usr/sbin, /usr/local/bin, etc directories. As system administrators, we would have to write many shell scripts to do a few tasks or
4 min read
Bash Scripting - Introduction to Bash and Bash Scripting Bash is a command-line interpreter or Unix Shell and it is widely used in GNU/Linux Operating System. It is written by Brian Jhan Fox. It is used as a default login shell for most Linux distributions. Scripting is used to automate the execution of the tasks so that humans do not need to perform them
12 min read
Bash Script - Define Bash Variables and its types Variables are an important aspect of any programming language. Without variables, you will not be able to store any required data. With the help of variables, data is stored at a particular memory address and then it can be accessed as well as modified when required. In other words, variables let yo
12 min read
Bash Script - Difference between Bash Script and Shell Script In computer programming, a script is defined as a sequence of instructions that is executed by another program. A shell is a command-line interpreter of Linux which provides an interface between the user and the kernel system and executes a sequence of instructions called commands. A shell is capabl
4 min read
Batch Script - Printing / NETPrint Command A Bash script is similar to a simple text file that contains a number of commands that the programmer can write in a command line. In Unix-based systems, these commands are used for performing repetitive tasks. A Bash script consists of a bunch of commands, or it may contain elements like loops, fun
3 min read
How to Create a Shell Script in linux Shell is an interface of the operating system. It accepts commands from users and interprets them to the operating system. If you want to run a bunch of commands together, you can do so by creating a shell script. Shell scripts are very useful if you need to do a task routinely, like taking a backup
7 min read
How to Check the Syntax of a Bash Script Without Running It? A bash script is a text file that contains a sequence of commands that are executed by the bash shell, a Unix-based command-line interface. Bash scripts are used to automate tasks, create utility scripts, and perform a wide range of other functions in the command-line environment. They can include v
5 min read
Shell Scripting - Define #!/bin/bash A shell provides an interface to connect with the system. When we use an operating system, we indirectly interact with the shell. While using a terminal every time on any Linux distribution system, we interact with the shell. The main function of the shell is to interpret or analyze Unix commands. A
3 min read
Introduction to Linux Shell and Shell Scripting If we are using any major operating system, we are indirectly interacting with the shell. While running Ubuntu, Linux Mint, or any other Linux distribution, we are interacting with the shell by using the terminal. In this article we will discuss Linux shells and shell scripting so before understandi
8 min read