Introduction to Z Shell Scripting
local graph
Chapter 22 — Introduction to Z Shell Scripting
Section titled “Chapter 22 — Introduction to Z Shell Scripting”Thus far, we’ve mainly talked about bash, since it’s the preeminent login shell and scripting environment for Linux. In recent years, a fairly new kid on the block, Z Shell (zsh) has been gaining a bit of popularity as a default login shell. But, even on the operating systems that come with zsh as the login shell, bash is still there, and bash is what most people still use for scripting purposes. Be aware though, that scripting in zsh does have certain advantages, such as better math capabilities, enhanced variable expansion, and the ability to use native zsh commands instead of utilities such as find, grep, or sed. These features can help you create scripts that are a bit simpler and lighter than equivalent bash scripts.
Most articles and YouTube videos that you see about zsh focus on the user interface enhancements, and very few focus on zsh scripting. Unfortunately, the few books and tutorials that do focus on zsh scripting aren’t very well-written, and you won’t get much out of them. Hopefully, I can provide some clarification.
Rather than present a detailed tutorial, I’d like to just present a high-level overview of zsh scripting, so that you can decide for yourself if it’s for you.
Topics in this chapter include:
- Introducing zsh
- Installing zsh
- Understanding the Unique Features of zsh Scripting
- Using zsh Modules
If you’re ready, let’s dig in.
Technical Requirements
You can use any of your Linux virtual machines for this chapter. As always, you can grab the demo scripts by doing:
git clone https://github.com/PacktPublishing/The-Ultimate-Linux-Shell-Scripting-Guide.gitIntroducing zsh
Z Shell was created in 1990 by Paul Falstad. It’s an extension of the Bourne Shell, but also includes features from bash, Korn Shell (ksh), and C Shell (tcsh).
The C Shell, which used to be somewhat popular with Unix and Unix-like distros, is vastly different from anything you’ve seen. Writing a C Shell script is more akin to writing a C language program than it is to what you’re used to. So if you’re a C language programmer, you might like it. If you’re not, then you might not like it so much.
Z Shell comes as the default login shell for both macOS and Kali Linux. For pretty much everything else, you’ll need to install it yourself. As far as zsh scripting goes, most of what you’ve learned about scripting in bash also applies to scripting in zsh. So, in this chapter I’ll just present the unique features of zsh, and show you some simple scripting examples.
Installing zsh
The zsh package is available in all Linux and BSD-type distros that I’ve tried, as well as on OpenIndiana. The package name is zsh in all cases, so you can just install it with your normal package manager.
On the BSD distros, you’ll have the same path problem that you had with bash. That is, on BSD distros, the zsh executable is in the /usr/local/bin/ directory, instead of the /bin/ directory. That’s okay, though. Just create a symbolic link in the /bin/ directory, as you did for bash. On my FreeBSD machine, the command looks like this:
donnie@freebsd-zfs:~ $ which zsh/usr/local/bin/zshdonnie@freebsd-zfs:~ $ sudo ln -s /usr/local/bin/zsh /bin/zshdonnie@freebsd-zfs:~ $ which zsh/bin/zshdonnie@freebsd-zfs:~ $Now, if you need to run your zsh scripts on Linux, OpenIndiana, and BSD machines, you can use the same shebang line, which looks like this:
#!/bin/zshIf you want to use zsh as your temporary login shell, you can just enter zsh at your normal shell’s command prompt. If you want to set zsh as your permanent login shell, use the chsh command on Linux and the BSD distros, and the passwd command on OpenIndiana. Here’s how that looks on Linux and the BSD distros:
donnie@ubuntu2404:~$ chsh -s /bin/zshPassword:donnie@ubuntu2404:~$Here’s how it looks on OpenIndiana:
donnie@openindiana:~$ passwd -eEnter existing login password:Old shell: /bin/bashNew shell: /bin/zshpasswd: password information changed for donniedonnie@openindiana:~$Note that when you change the shell for your own user account, you’ll be prompted to enter your own user password. However, this has nothing to do with sudo, because even non-privileged users can use chsh on Linux/BSD distros and passwd -e on OpenIndiana to change their own default shells.
The first time you log in with zsh, you’ll be presented with a setup menu that looks like this:
This is the Z Shell configuration function for new users,zsh-newuser-install.You are seeing this message because you have no zsh startup files(the files .zshenv, .zprofile, .zshrc, .zlogin in the directory~). This function can help you with a few settings that shouldmake your use of the shell easier.
You can:
(q) Quit and do nothing. The function will be run again next time.
(0) Exit, creating the file ~/.zshrc containing just a comment.That will prevent this function being run again.
(1) Continue to the main menu.
--- Type one of the keys in parentheses ---Hit the 1 key to go to the main menu, and choose your preferred setup options. The configuration will be saved to the .zshrc file in your home directory.
Next, let’s look at some of the unique features of zsh scripting.
Understanding the Unique Features of zsh Scripting
When you script in zsh, you can take advantage of certain enhancements that aren’t in bash. Here’s a quick review of some of those enhancements.
Differences in Variable Expansion
Section titled “Differences in Variable Expansion”In Chapter 8—Basic Shell Script Construction, I explained the concept of variable expansion, which is also sometimes called parameter expansion. This allows you to write cool scripts that do cool things, such as changing the filename extensions on a whole batch of files at a time. Most of the same variable expansion constructs that are in bash are also in zsh, but zsh has additional ones that provide additional capabilities. Let’s look at a few examples.
Substituting Values
Section titled “Substituting Values”Substituting values in zsh works the same as it does in bash, with one exception. That is, if you substitute a value in a text string that includes an exclamation point, you’ll have to escape it in a zsh script. For example, here’s how it works in bash:
donnie@fedora:~$ unset namedonnie@fedora:~$ echo "Hello, ${name:-Guest}!"Hello, Guest!donnie@fedora:~$ name=Horatiodonnie@fedora:~$ echo "Hello, ${name:-Guest}!"Hello, Horatio!donnie@fedora:~$As I explained in Chapter 8, the variable_name:-default_value construct supplies a default value for any variable that doesn’t yet have a value assigned to it. This same construct is supposed to work in zsh, but watch what happens when I try it:
ubuntu2404% unset nameubuntu2404% echo "Hello, ${name:-Guest}!"dquote> "Hello, Guestubuntu2404%When I hit the Enter key after typing the echo command, zsh takes me to the dquote> prompt. If I hit the ” key a second time, I get the output that I want. To get it right the first time, I’ll just place a \ before the !, like this:
ubuntu2404% unset nameubuntu2404% echo "Hello, ${name:-Guest}\!"Hello, Guest!ubuntu2404% name=Horatioubuntu2404% echo "Hello, ${name:-Guest}\!"Hello, Horatio!Ubuntu2404%So, with the \ in front of the exclamation point, it works just fine. I don’t know why the escaped in zsh, but whatever works, right?
Substituting Substrings
Substring substitution partly works in bash, but not completely. Here’s what I mean.
I’ll first create the name variable with the value of lionel. Then, on both bash and zsh, I’ll attempt to replace the first lower-case l with an upper-case L. First, on bash, like so:
donnie@fedora:~$ echo $SHELL/bin/bashdonnie@fedora:~$ name="lionel"donnie@fedora:~$ echo "${name/l/L}"Lioneldonnie@fedora:~$Now, on zsh:
ubuntu2404% echo $SHELL/bin/zshubuntu2404% name="lionel"ubuntu2404% echo "${name/l/L}"Lionelubuntu2404%In the ${name/l/L} construct, you see that I first listed the variable name with a forward slash and the letter that I want to replace, followed by another forward slash and the letter that I want to substitute. As you can see, this works on both bash and zsh. I can also replace both occurrences of the lower-case l by using two forward slashes after the name variable, like so:
On bash:
donnie@fedora:~$ echo "${name//l/L}"Lioneldonnie@fedora:~$On zsh:
ubuntu2404% echo "${name//l/L}"Lionelubuntu2404%Again, this works on both bash and zsh. So, if this works on both shells, why am I showing this to you? Well, it’s just that on bash, this only works if the text string doesn’t contain any blank spaces.
Here’s an example of what I mean:
On bash:
donnie@fedora:~$ names="Donnie and Vicky and Cleopatra"donnie@fedora:~$ echo "${names//and/&}"Donnie and Vicky and Cleopatradonnie@fedora:~$This time, I wanted to replace all occurrences of and with an ampersand. But, this doesn’t work on bash because the text string contains blank spaces. So, let’s try this on zsh.
On zsh:
ubuntu2404% names="Donnie and Vicky and Cleopatra"ubuntu2404% echo "${names//and/&}"Donnie & Vicky & Cleopatraubuntu2404%sh, having a text string with blank spaces doesn’t matter.
Translating Between Upper and Lower Case
Section titled “Translating Between Upper and Lower Case”Here’s an example of the exact opposite situation. This time, I’ll show you something that works on bash, but not on zsh. Then, I’ll show you the alternative method for zsh.
First, let’s say that we want to capitalize the first letter of the value that’s assigned to the name variable. Here’s how to do it on bash:
donnie@fedora:~$ name=horatiodonnie@fedora:~$ echo "${name^}"Horatiodonnie@fedora:~$All I did here was to place a ^ after the name variable in the echo statement. Now, let’s say that I want to capitalize all letters. I’ll do that by using two ^ characters, like this:
donnie@fedora:~$ echo "${name^^}"HORATIOdonnie@fedora:~$If you have a text string with all upper-case characters, use either one or two commas to convert either the first letter or all letters to lower-case, like this:
donnie@fedora:~$ name=HORATIOdonnie@fedora:~$ echo "${name,}"hORATIOdonnie@fedora:~$ echo "${name,,}"horatiodonnie@fedora:~$On zsh, none of this works at all, as you see here:
ubuntu2404% name=horatioubuntu2404% echo "${name^}"zsh: bad substitutionubuntu2404% echo "${name^^}"zsh: bad substitutionubuntu2404% name=HORATIOubuntu2404% echo "${name,}"zsh: bad substitutionubuntu2404% echo "${name,,}"zsh: bad substitutionubuntu2404%I’m showing you this because some zsh scripting books say this will work on zsh. But, as you see, it definitely doesn’t.
So, what’s the alternative on zsh? Well, you just use a builtin zsh function. Let’s first use the U function to convert an entire text string to upper-case:
ubuntu2404% name=horatioubuntu2404% echo "${(U)name}"HORATIOubuntu2404%Instead of placing a pair of ^ characters after the name variable, I just placed a (U) before the name variable.
As far as I’ve been able to find, there’s no function that converts just the first letter. So, let’s convert the first letter like this, instead:
ubuntu2404% name=horatioubuntu2404% capitalized_name=${name/h/H}ubuntu2404% echo $capitalized_nameHoratioubuntu2404%This is the same method that I’ve just shown you in the previous section.
Next, let’s do some globbing.
Extended File Globbing
Section titled “Extended File Globbing”“What’s file globbing”, you say? Well, you’ve actually been working with it throughout this book. It’s just that I’ve never told you what it’s called. All it means is that you can use wildcard characters, such as the * and the ?, to work with multiple files at the same time. For example, you can do this:
donnie@fedora:~$ ls -l *.zip-rw-r--r--. 1 root root 32864546 Jul 27 2023 15827_zip.zip-rw-r--r--. 1 root root 49115374 Jul 27 2023 21261.zip-rw-r--r--. 1 root root 36996449 Jul 27 2023 46523.zip......-rw-r--r--. 1 root root 21798397 Jul 27 2023 tmvx.zip-rw-r--r--. 1 root root 60822 Jul 27 2023 U_CAN_Ubuntu_20-04_LTS_V1R4_STIG_SCAP_1-2_Benchmark.zip-rw-r--r--. 1 root root 425884 Jul 27 2023 zoneinfo.zipjonnie@fedora:~$All I’m doing here is using the * wildcard to view all of the .zip files in my directory.
You can do all this and more in zsh. The only catch is that you need to have the extendedglob feature turned on. To verify that it is, look in the .zshrc file in your home directory. You should see a line that looks something like this:
setopt autocd beep extendedglob nomatch notifyIf the extendedglob option is there, then you’re good. If it isn’t, just add it in. So now, let’s look at a few examples of extended globbing.
Why is extended file globbing on zsh useful? Well, it’s just that in many cases, you’ll be able to use the extended globbing features of zsh instead of using the find utility. You might find this easier than using find. Or, you might prefer using find, if that’s what you’re used to using. I’ll let you make the decision.
Also, for demo purposes, I’m mainly showing you this with the ls utility. But, you can also use globbing with other utilities, such as cp, mv, rm, chmod, or chown.
Filtering ls Output
Section titled “Filtering ls Output”With this cool feature enabled, you can do cool things like excluding files that you don’t want to see. For example, let’s say that you want to see all files in your directory except for the .sh files. Just do this:
ubuntu2404% ls -d ^*.shbashlib-0.4 My_Filesdemo_files supersecretdeshc-deb supersecret_trace.txtDocuments sysinfo.html<!-- page: 604 (printed 607) -->encrypted_password sysinfo_posix.libencrypted_password.sh.x.c test.sh.xexpand_1.txt user_activity_for_donnie_2024-05-12_09-30.txtexpand_2.txt user_activity_for_donnie_2024-07-22_10-40.txtexpand.txt user_activity_for_horatio_2024-07-06_07-12.txtFallOfSudo while_demofile2.txt while_demo.sh.x.cfile3.jpgubuntu2404%The ^ that precedes the *.sh is a negation symbol. This is what prevents the ls command from showing you the .sh files.
Note that I had to include the -d option for ls. Otherwise, you’ll also see files in any sub-directories that you might have. For some reason, the ^ filters out the unwanted files in my top level directory, but it doesn’t filter out the unwanted files in the subdirectories. So, without the -d, you’ll also see all files that are in the subdirectories, including the ones that you want to filter out.
You can use the *~ operator to accomplish the same thing. Here’s how that looks:
ubuntu2404% ls -d *~*.shbashlib-0.4 My_Filesdemo_files supersecretdesch-deb supersecret_trace.txtDocuments sysinfo.htmlencrypted_password sysinfo_posix.libencrypted_password.sh.x.c test.sh.xexpand_1.txt user_activity_for_donnie_2024-05-12_09-30.txtexpand_2.txt user_activity_for_donnie_2024-07-22_10-40.txtexpand.txt user_activity_for_horatio_2024-07-06_07-12.txtFallOfSudo while_demofile2.txt while_demo.sh.x.cfile3.jpgubuntu2404%As you see, the output is identical to that of the ls -d ^ .sh output. To exclude multiple types of files, just use the or operator (|), like this:
ubuntu2404% ls -d *~(*.sh|*.jpg|*.txt|*.c)bashlib-0.4 Documents My_Files sysinfo_posix.libdemo_files encrypted_password supersecret test.sh.xdesch-deb FallOfSudo sysinfo.html while_demoubuntu2404%So in this case, I filtered out the .sh, .jpg, .txt, and .c files. Now, let’s look at our next trick.
Grouping ls Searches
Something else that you can’t do in bash is to group your ls searches, like this:
ubuntu2404% ls -ld (ex|test)*-rw-r--r-- 1 donnie donnie 52 Apr 29 20:02 expand_1.txt-rw-r--r-- 1 donnie donnie 111 Apr 29 20:02 expand_2.txt-rw-r--r-- 1 donnie donnie 51 Apr 29 20:02 expand.txt-rwxrwxr-x 1 donnie donnie 48 Jun 30 20:26 test.sh-rw-rw-r-- 1 donnie donnie 0 Jul 5 19:31 test.sh.dec.sh-rwxr-xr-x 1 donnie donnie 11440 Jul 5 19:12 test.sh.xubuntu2404%Here, I’m using the | symbol as an or operator, to view all files with either ex or test as the first portion of their filenames.
Using Globbing Flags
You know, Linux and Unix operating systems are normally case-sensitive. So, if you were to use the *.jpg command to view all JPEG-type graphics files, you would completely miss any files might have the *.JPG extension. With zsh, you can use globbing flags to make your commands case-insensitive. Here’s an example:
ubuntu2404% touch graphic1.jpg graphic2.JPG graphic3.jpg file3.jpgubuntu2404% ls *.jpgfile3.jpg graphic1.jpg graphic3.jpgubuntu2404% ls (#i)*.jpgfile3.jpg graphic1.jpg graphic2.JPG graphic3.jpgubuntu2404%The (#i) in the second ls command is the globbing flag. The # indicates that it’s a flag, and it will precede the pattern that you want to match.
The (#1) flag will match either a lower-case or upper-case pattern if you specify a lower-case pattern for your search. If you specify an upper-case pattern, then it will only match the upper-case pattern. Here’s how that looks:
ubuntu2404% ls (#1)*.jpgfile3.jpg graphic1.jpg graphic2.JPG graphic3.jpgubuntu2404% ls (#1)*.JPGgraphic2.JPGubuntu2404%You see here that when I specified *.jpg as the pattern, it also found the .JPG file. But, when I specified .JPG as the pattern, it only found the .JPG file.
Now, let’s expand some directories.
Expanding Directories
Section titled “Expanding Directories”You can use globbing qualifiers to view different types of directories or files. We’ll start with the qualifiers for directories, which are:
- (F): This expands non-empty directories.
- (^F): This expands both plain files and empty directories.
- (/^F): This only expands empty directories.
First, let’s look at the non-empty directories that are in my home directory.
ubuntu2404% ls *(F)bashlib-0.4:bashlib config.cache config.status COPYING Makefile READMEbashlib.in config.log configure INSTALL Makefile.in
...
My_Files:afile.txt somefile.txt yetanotherfile.txtanotherfile.txt somepicture.jpg yetanotheryetanotherfile.txthaveicreatedenoughfilesyet.txt somescript.sh
ubuntu2404%You see here that this command shows the non-empty directories and their contents. But, it doesn’t show any files that are in my top-level home directory. So, it’s all good.
Now, I want to see all of the files that are in my top-level home directory, along with any empty directories that might also be there. I’ll do that like this:
ubuntu2404% ls *(^F)acl_demo.sh rsync_password.shdiskspace.sh shutdown-update.sh
...
rootlock_2.sh while_demo.sh.x.c
Documents:
empty_directory:ubuntu2404%The two empty directories show up at the bottom of the output.
Finally, I only want to see the empty directories, like so:
ubuntu2404% ls *(/^F)Documents:
empty_directory:ubuntu2404%Pretty cool, eh? Next, let’s look at file expansion.
Expanding Files There are several ways to expand files. First, we’ll expand by either the file or directory file types.
Expanding Files and Directories If you want to see the files in your directory, but don’t want to see any directories, do this:
ubuntu2404% ls *(.)acl_demo.sh rsync_password.shdiskspace.sh shutdown-update.shencrypted_password sudo_demo1.sh......rootlock_1.sh while_demo.shrootlock_2.sh while_demo.sh.x.cubuntu2404%If you only want to see your directories, both empty and non-empty, do this:
ubuntu2404% ls *(/)bashlib-0.4:bashlib config.cache config.status COPYING Makefile READMEbashlib.in config.log configure INSTALL Makefile.in......Documents:
empty_directory:
FallOfSudo:fallosudo.py LICENSE main.png README.md
My_Files:
<!-- page: 608 (printed 611) -->
afile.txt somefile.txt yetanotherfile.txtanotherfile.txt somepicture.jpg yetanotheryetanotherfile.txthaveicreatedenoughfilesyet.txt somescript.shubuntu2404%Okay, I think you see what’s going on with this. Let’s move on to look at file permissions.
Expanding by File Permissions
In Chapter 20, Shell Script Security, I explained about how file and directory permissions work. Let’s do a quick review.
The permissions settings are divided between the user—which is what we call the owner of the file or directory—the group, and others. Each of these can have any combination of read, write, and executable permissions set for any given file or directory. If you need to search for files or directories with certain permissions settings, you can use the find utility. On zsh, you can use globbing qualifiers instead of find. Here’s the list of the qualifiers that you’ll work with:
For the user:
- r: The user has the read permission.
- w: This denotes files for which the user has the write permission.
- x: The user has the executable permission.
- U: This looks for files or directories that belong to the current user.
- s: This looks for files with the SUID permission set.
For the group:
- A: The group has the read permission.
- I: The group has the write permission.
- E: The group has the executable permission.
- G: This looks for files or directories that belong to the current user’s group.
- S: This looks for files or directories that have the SGID permission set.
For others:
- R: Others have the read permission.
- W: Others have the write permission.
- X: Others have the executable permission.
- t: This looks for directories that have the sticky bit set.
So, how does all this work? Well, let’s say that you’re in the /bin/ directory, and you want to see all of the files that have the SUID permission set. Just do something like this:
ubuntu2404% cd /binubuntu2404% ls -ld *(s)-rwsr-xr-x 1 root root 72792 Apr 9 07:01 chfn
<!-- page: 609 (printed 612) -->
-rwSr-xr-x 1 root root 44760 Apr 9 07:01 chsh-rwSr-xr-x 1 root root 39296 Apr 8 15:57 fusermount3-rwSr-xr-x 1 root root 76248 Apr 9 07:01 gpasswd-rwSr-xr-x 1 root root 51584 Apr 9 14:02 mount-rwSr-xr-x 1 root root 40664 Apr 9 07:01 newgrp-rwSr-xr-x 1 root root 64152 Apr 9 07:01 passwd-rwSr-xr-x 1 root root 55680 Apr 9 14:02 su-rwSr-xr-x 1 root root 277936 Apr 8 14:50 sudo-rwSr-xr-x 1 root root 39296 Apr 9 14:02 umountubuntu2404%If you’re in your own home directory and want to see all of the SUID files that are on the entire filesystem, just make your search recursive, like this:
ubuntu2404% ls -ld /**/*(s)-rwSr-xr-x 1 root root 85064 Feb 6 2024 /snap/core20/2264/usr/bin/chfn-rwSr-xr-x 1 root root 53040 Feb 6 2024 /snap/core20/2264/usr/bin/chsh......-rwSr-xr-x 1 root root 154824 Jul 26 02:32 /usr/lib/snapd/snap-confineubuntu2404%Unlike find, ls isn’t inherently recursive. So, if want to search through all of the lower-level subdirectories of the directory you’re already in, just do this:
ubuntu2404% pwd/home/donnieubuntu2404% ls -l **/*(s)zsh: no matches found: **/*(s)ubuntu2404%The only difference between this and the full filesystem search is that I used /*(s) instead of //*(s). (Of course, there are no SUID files in my home directory, which is to be expected.)
If you need to actually do something with this ls output, you can create a zsh script, like this find_suid.sh script:
#!/bin/zsh
ls -ld /**/*(s) > suid_files.txtIt’s just a simple little script that creates a text file with a list of the SUID files on your system. But hey, who says we can’t fancy it up a bit? Let’s see what we can do in the find_suid2.sh script:
#!/bin/zsh
suid_results_file=$1
if [[ -f "$suid_results_file" ]]; then echo "This file already exists." exitfils -ld /**/*(s) > "$suid_results_file"With this script, you’ll specify the name of the file where you want the results to be saved. If there’s already a file with that filename, the script will give you a warning message and then exit.
You can use any of the other globbing qualifiers in the same manner. For example, let’s say that you need to search through the entire filesystem for files that belong to you. Let’s see how that works:
ubuntu2404% ls -ld /**/*(U) | lessThis will make for a very long list, so I have to pipe this into less to prevent the output from scrolling off the top of the screen. Here’s some of what you’ll see:
crw--w---- 1 donnie tty 136, 0 Sep 3 20:04 /dev/pts/0crw------- 1 donnie tty 4, 1 Sep 3 19:24 /dev/tty1drwxr-x--- 13 donnie donnie 4096 Sep 3 20:02 /home/donnie-rw-rw-r-- 1 donnie donnie 44 Jul 24 20:53 /home/donnie/acl_demo.shdrwxr-xr-x 2 donnie donnie 4096 Jun 29 21:10 /home/donnie/bashlib-0.4......-rw-r--r-- 1 donnie donnie 0 Sep 3 19:24 /sys/fs/cgroup/user.slice/user-1000.slice/[email protected]/memory.reclaim-rwxrwxrwx 1 donnie donnie 2155 Jul 5 19:31 /usr/bin/deshcAs you see, a typical Linux system has files that belong to you all over the place.
This is one clear advantage that zsh has over every other shell, including bash. The extended file globbing capabilities of zsh can replace much of the functionality of find, but with much simpler syntax. (Of course, you can also use this trick with other utilities besides ls, such as cp, mv, rm, chmod, or chown.)
You can also use zsh file globbing to replace utilities such as grep, awk and tr. Honestly though, the syntax for globbing commands that replace those utilities is so convoluted that you’re better off using the utilities. On the other hand, using zsh file globbing instead could make your scripts somewhat lighter and faster. And, you can use file globbing in those rare cases where you might find that the utilities aren’t installed.
At any rate, if you want to read about the additional file globbing capabilities of zsh, here’s the link:
Zsh Native Scripting Handbook:
https://github.zshell.dev/docs/zsh/Zsh-Native-Scripting-Handbook.html
You can also find out more about both file globbing and variable expansion by reading the zshexpn man page.
All right, let’s talk briefly about arrays.
Understanding zsh Arrays
This will be quick, because there are only three things that I want to point out about zsh arrays. The first thing is that instead of having array index numbers begin with 0, as is the case with bash arrays, the index numbers for zsh arrays begin with 1. Here’s how it looks on bash:
donnie@fedora:~$ mybasharray=(vicky cleopatra horatio)donnie@fedora:~$ echo ${mybasharray[0]}vickydonnie@fedora:~$ echo ${mybasharray[1]}cleopatradonnie@fedora:~$You see how using an index number of 0 brings up the first name in the list, and an index number of 1 brings up the second name. Now, here’s how it looks on zsh:
ubuntu2404% myzsharray=(vicky cleopatra horatio)ubuntu2404% echo ${myzsharray[0]}
ubuntu2404% echo ${myzsharray[1]}vickyubuntu2404% echo ${myzsharray[2]}cleopatraubuntu2404%This time, the index number of 0 brings up nothing, because index 0 doesn’t exist.
The second big difference is in how you can view the entire contents of an array. With bash, you need to do something like this:
donnie@fedora:~$ echo ${mybasharray[@]}vicky cleopatra horatiodonnie@fedora:~You can still do this on zsh if you like, but you don’t have to. Instead, you can just view the contents of the array the same as you’d view the value of a normal variable, like this:
ubuntu2404% echo $myzsharrayvicky cleopatra horatioubuntu2404%Finally, I want to show you how to eliminate duplicate entries that might be in an array. To demonstrate, let’s create an array with a list of fruits, like this:
ubuntu2404% fruits=(orange apple orange banana kiwi banana apple orange)ubuntu2404% echo $fruitsorange apple orange banana kiwi banana apple orangeubuntu2404%As you see, there are several duplicates in the list. To get rid of the duplicates, just do this:
ubuntu2404% echo ${(u)fruits}orange apple banana kiwiubuntu2404%Replacing the (u) with (U) prints out the entire list in upper-case letters.
ubuntu2404% echo ${(U)fruits}ORANGE APPLE ORANGE BANANA KIWI BANANA APPLE ORANGEubuntu2404%Combine the u with the U, and you’ll eliminate duplicates and print out the list in upper-case letters.
ubuntu2404% echo ${(uU)fruits}ORANGE APPLE BANANA KIWIubuntu2404%To show this in practice, let’s look at the fruit_array.sh script:
#!/bin/zsh
fruits=(apple orange banana apple orange kiwi)echo "Let's look at the entire list of fruits."for fruit in $fruits; doGrouping math operations, in order to specify their precedence, looks like this:
ubuntu2404% ((product=(2.1+2.1)*8))ubuntu2404% echo $product33.600000000ubuntu2404%If just simple math isn’t enough for you, you can load the mathfunc module, which I’ll show you in the next section.
Using zsh Modules
Section titled “Using zsh Modules”A lot of zsh functionality is contained in loadable zsh modules. I can’t cover all of the zsh modules in this chapter, so let’s just look at some of the more useful ones.
First, let’s see which modules get loaded into a zsh session by default:
ubuntu2404% zmodloadzsh/completezsh/computilzsh/mainzsh/parameterzsh/statzsh/terminfozsh/zlezsh/zutilubuntu2404%There are a lot more optional modules that you can load yourself by using the zmodload command, as we’ll see next.
To read about all of the available zsh modules, see the zshmodules man page.
Now, let’s get a bit more specific by looking at the mathfunc module.
Using the mathfunc Module
Section titled “Using the mathfunc Module”If you want to create some really fancy math scripts without having to use an external utility such as bc, just load the mathfunc module, like this:
ubuntu2404% zmodload zsh/mathfuncubuntu2404%This module provides functions for trigonometry, logarithms, exponentiation, as well as some other math functions. You can see all the functions that the modules provide, like this:
ubuntu2404% zmodload -lF zsh/mathfunc+f:abs+f:acos+f:acosh+f:asin+f:asinh......+f:y0+f:y1+f:ynubuntu2404%So now, let’s say that you want to see the square root of 9. Do it like this:
ubuntu2404% ((squareroot=sqrt(9)))ubuntu2404% echo $squareroot3.000000000ubuntu2404%Now, let’s put this into the squareroot.sh script:
#!/bin/zshzmodload zsh/mathfuncyour_number=$1((squareroot=sqrt(your_number)))echo $squarerootNote here that I’ve had to place a zmodload zsh/mathfunc command at the beginning of this script. That’s because every time you close your terminal or log out of your machine, any modules that you’ve loaded from the command-line will automatically unload. So, you’ll have to add this zmodload command to your scripts.
Here, I’m using the your_number variable to contain the value of the number that the user specifies for the $1 parameter. Let’s see if it works.
ubuntu2404% ./squareroot.sh 93.000000000ubuntu2404% ./squareroot.sh 255.000000000ubuntu2404% ./squareroot.sh 2<!-- page: 615 (printed 620) -->1.4142135624ubuntu2404%Oh yeah, it works just fine, and all without messing with any external programs, such as bc.
All of the other mathfunc functions work in a similar manner. Use your own imagination and the scripting concepts that I’ve shown you for bash to come up with your own zsh math scripts.
That does it for your introduction of the mathfunc module. Next, let’s briefly look at the datetime module.
The datetime Module
Section titled “The datetime Module”The datetime module does pretty much the same job as the date utility. You can use either one to do cool things, like creating files with timestamps in their filenames. It’s not loaded by default, so let’s do that now:
ubuntu2404% zmodload zsh/datetimeubuntu2404%Now, let’s see what it provides:
ubuntu2404% zmodload -lF zsh/datetime+b:strftime+p:EPOCHSECONDS+p:EPOCHREALTIME+p:epochtimeubuntu2404%Here’s the breakdown of what you’re looking at:
- strftime: This is the only function that this module contains. You can use it the same as you’d use the date utility.
- EPOCHSECONDS: This environmental variable is an integer value that represents the number of seconds that have elapsed since the beginning of the Unix epoch. This variable is also available in bash.
- EPOCHREALTIME: This environmental variable is a floating point value that represents the number of seconds that have elapsed since the beginning of the Unix epoch. Depending upon the particular system, this value can be to either nanosecond or microsecond accuracy. This variable is also available in bash.
- epochtime: This variable contains two components. It’s like the EPOCHREALTIME variable, except that the decimal point is replaced by a blank space. This variable is not available in bash.
The Unix epoch began on 1 January, 1970. In the early days of Unix, Unix developers decided that the easiest way to set the time on a Unix computer would be to express it as the number of seconds that have elapsed since that date.
You can see the current values of the three variables like this:
ubuntu2404% echo $EPOCHSECONDS1725470539ubuntu2404% echo $EPOCHREALTIME1725470545.8938724995ubuntu2404% echo $epoctime1725470552 124436538ubuntu2404%Now, let’s create the zsh_time.sh script that uses the strftime function:
#!/bin/zshzmodload zsh/datetime
timestamp=$(strftime '%A-%F_%T')echo "I want to create a file at $timestamp." > "timefile_$timestamp.txt"The strftime function uses the same date and time formatting options as the date utility uses. In this case we have:
- %A: This is the day of the week.
- %F: This is the date in YYYY-MM-DD format.
- %T: This is the time in HH:MM:SS format.
The only real difference between using date and strftime is that with date, you have to precede the string of formatting options with a +, like this:
date +'%A-%F-%T'The strftime function has its own man page, which you can view by doing man strftime.
After I run the script, I should have my file:
ubuntu2404% ./zsh_time.shubuntu2404% ls -l timefile_*-rw-rw-r-- 1 donnie donnie 58 Sep 4 18:16 timefile_Wednesday-2024-09-04_18:16:37.txt