Bash Scripting
Test
test is a bash built-in function to add conditionals in your script. [ is an alias of the test command and are analogous.
Use the test operators listed below with test or a single bracket test condition like the following example.
$ test -e /etc/hosts && echo "File exists"
File exists
## Note that the white space around [ and ] and also the operator are required.
$ [ -e /etc/hosts ] && echo "File exists"
File exists
$ if [ -e /etc/hosts ] ; then echo "File exists" ; fi
File exists
| Operator | Description | |
|---|---|---|
-e
|
file exists | |
-a
|
file exists (deprecated)
This is identical in effect to | |
-f
|
file is a regular file (not a directory or device file) | |
-s
|
file is not zero size | |
-d
|
file is a directory | |
-b
|
file is a block device. Eg. /dev/sda.
| |
-c
|
file is a character device. Eg. /dev/tty0.
| |
-p
|
file is a pipe. Eg. /dev/fd/0.
| |
-h
|
file is a symbolic link | |
-L
|
file is a symbolic link | |
-S
|
file is a socket | |
-t
|
file (descriptor) is associated with a terminal device
This test option may be used to check whether the stdin [ -t 0 ] or stdout [ -t 1 ] in a given script is a terminal. | |
-r
|
file has read permission (for the user running the test) | |
-w
|
file has write permission (for the user running the test) | |
-x
|
file has execute permission (for the user running the test) | |
-g
|
file or directory has set-group-id (sgid) flag set
If a directory has the sgid flag set, then a file created within that directory belongs to the group that owns the directory. | |
-u
|
file has set-user-id (suid) flag set | |
-k
|
file or directory has sticky bit set
| |
-O
|
you are owner of file | |
-G
|
group-id of file same as yours | |
-N
|
file modified since it was last read | |
f1 -nt f2
|
file f1 is newer than f2 | |
f1 -ot f2
|
file f1 is older than f2 | |
f1 -ef f2
|
files f1 and f2 are hard links to the same file | |
!
|
"not" -- reverses the sense of the tests above (returns true if condition absent). |
Integer
Integer tests, with test or inside single brackets.
Eg.
$ test 2 -eq 2 && echo equal
| Operator | Description |
|---|---|
-eq
|
is equal to |
-ne
|
is not equal to |
-gt
|
is greater than |
-ge
|
is greater than or equal to |
-lt
|
is less than |
-le
|
is less than or equal to |
Integer tests can aso be done inside double parentheses. Eg.
$ ((2==2)) && echo equal
| Operator | Description |
|---|---|
==
|
is equal |
<
|
is less than |
<=
|
is less than or equal to |
>
|
is greater than |
>=
|
is greater than or equal to |
Strings
| Operator | Description |
|---|---|
-z
|
string is null, that is, has zero length |
-n
|
string is not null. |
=
|
is equal to
## Does not work in zsh. Works only in sh and bash.
$ if [ "$a" = "$b" ] ; then
echo "Equal"
fi
|
==
|
is equal to
## Does not work in zsh. Works only in sh and bash.
$ if [ "$a" == "$b" ] ; then
echo "Equal"
fi
This operator inside a double bracket |
!=
|
is not equal to
$ if [ "$a" != "$b" ] ; then
echo "Not equal"
fi
This operator inside a double bracket |
=~
|
Match using regex
$ if [ zone36-ta =~ .*ta$ ] ; then
echo "matches"
fi
$ if [ zone36-ta =~ *ta ] ; then
echo "matches"
fi
|
Useful Functions / Utilities
Here are some common functions I use in my scripts.
Prompt
You can prompt the user for an yes or no answer using this function. An optional default values are accepted as the second argument.
Example Usage:
if prompt "Is this okay?" Y ; then
echo "It's Okay!"
fi
if ! prompt "Is this okay?" N ; then
echo "It's not okay!"
fi
Source: <phorkie>https://phorkie.leo.home.steamr.com/13/embed</phorkie>
die
Similar to the die command in PHP which prints out a message before stopping execution.
Function:
function die {
echo $@
exit
}
Caveat when using in a subshell
This will not work inside a subshell as it will just quit the subshell rather than the script. To get around this, you may need to kill the parent PID instead.
Indent
Indents text piped to the function.
Source: <phorkie>https://phorkie.leo.home.steamr.com/14/embed</phorkie>
Usage:
echo "test" | Indent
test
echo "test" | Indent 2
test
Extracting / Parsing Filenames
Use the basename to extract filenames from a path and and dirname to extract the path of a filename.
Eg:
$ dirname /etc/hosts
/etc
$ basename /etc/hosts
hosts
To extract only the extension or the filename without the extension, use bash's string matching:
Filename=$(basename /etc/resolv.conf)
Ext="${Filename##*.}"
Name="${Filename%.*}"
Arithmetic Operations
Do integer arithmetic operations on variables within double brackets. For example:
Value=1
ValuePlusOne=$((Value + 1))
ValueTimes12=$((Value * 12))
The operators that are supported are:
+ - / * %
Bitwise operators also work:
^ (XOR) | (OR) & (AND)
Control Blocks
Switch
read -p "What do you want to do?: " Option
case "$Option" in
"K")
install_new_kernel
die "Complete!"
;;
"H")
usage
;;
*)
die "Stopping installation."
;;
esac
Snippets
Get First IP Address
# ip a
See Also
- https://www.tldp.org/LDP/abs/html/comparison-ops.html
Various Linux Notes - /etc/fstab
- Access.conf
- ACL
- Apache Proxy to Internal Server
- APM X-C1 (Mustang)
- ARP
- Authselect
- Bash Scripting
- Blockparser
- Booting Linux without a Graphics Card
- Building Container Images
- Burning CD/DVD in Linux
- Clear RAID Signatures on Linux
- Cobbler
- Colorized Terminal Outputs
- Compiling MIPS
- Configure Sendmail
- CPanel
- CPanel Fork Bomb Protection
- CPU Frequency Scaling
- Create a Linux User with an Empty Password
- Cron and PAM Issues
- Dell OpenManage
- Diff Two Command Outputs
- DirectAdmin
- Disable Filesystem Check on Startup
- DNS Ad Blocker
- Driver Disk
- Drop caches
- End / Home keys don't work in Terminal
- Entropy in the Linux Kernel
- Entropy Source using RTL-SDR
- Exit Codes
- Extract .exe Resources with dd
- File Attributes
- Fixing ixgbe unsupported SFP+ module type was detected
- Get Active Linux Virtual Console
- Getting Hardware UUID
- Hosts.deny
- How to change Linux desktop user directories
- How to hot-swap SATA disks on Linux
- HP Smart Storage Administrator
- Hyper-threading
- IBM Spectrum Archive
- IBM Spectrum Protect
- IBM Tape
- IBM Tape Diagnostic Tool
- InterWorx
- Kerberize NFS
- Kerberize SSH
- Linux Clustering
- Linux Fonts
- Linux Namespaces
- Linux Network Interface Naming
- Linux Nvidia Driver
- Linux Process Accounting
- Linux Uptime in Seconds
- Linux UTF-8 Font
- Mainline Kernel on CentOS 7
- Missing Fonts
- Mod fastcgi Install on Apache 2 / cPanel
- Mod fcgid
- Monitoring network traffic in Linux
- Mounting / Unmounting KVM Image
- Mounting Samba (CIFS) shares
- Multiple Networks on Linux
- MySQL Database with Hash Sign
- No Console Output
- Number of Files Opened
- Open OnDemand
- Packing and unpacking initrd
- PAM Issues
- Partition Alignment
- Patching a binary file with dd
- Perl Module Location
- Raspberry Pi
- Red Hat kickstart
- Red Hat to Debian
- Reverse SSH Tunnel
- Ruby on Rails under cPanel
- Rutorrent + rtorrent Installation Guide on CentOS 6.4
- Self Signed SSL Certificates
- Service Management
- Sick Beard
- StartSSL Free Certificate
- Symlink
- Taking a Screenshot in X11
- Timezone
- Tor
- TOR Transparent Proxy
- Traefik
- Troubleshooting a Slow Linux System
- Turning on swap with a page file
- Udev Rules
- Verify SSL Certificate matches Private Key
- VMware Workstation
- Webcam
- X Display Manipulation
- X Forwarding
Linux Tools and Utilites - Anaconda
- Ansible
- Aria2
- Autofs
- Awk
- Badblocks
- Bash Shell
- Binwalk
- Bosh
- Ceph
- Chntpw
- Chrony
- Clonezilla
- Cloud-init
- CloudStack
- Column
- Cron
- Curl
- Cvs2git
- Date
- Dbus
- Dd
- Dm-crypt
- Dovecot
- DRBD
- ElasticSearch
- Enroot
- Environment Module
- Envsubst
- Fail2ban
- FFmpeg
- Find
- Firecracker
- Flashrom
- Foreman
- FortiClient
- Fswebcam
- Galaxy
- Git
- Gnome
- Gobetween
- GPFS
- Grafana
- Grub
- Hdparm
- Home Assistant
- How to disable SELinux
- Htaccess
- Infiniband
- InfluxDB
- InfluxDB 1.x
- Insert a kickstart file into a iso image
- Inspircd
- IOzone
- Iperf3
- Ipmitool
- Irqbalance
- John The Ripper
- Lightdm
- Lm sensors
- Logrotate
- LSF
- LVM
- Lynx
- Mailx
- Md5sum
- Mdadm
- Midnight Commander
- Motion
- Mount
- Mutt
- Nomad
- OpenLDAP
- Openocd
- OpenSSL
- OpenVPN
- Packer
- PHP
- Pi-hole
- Postgres
- PowerBroker Identity Service
- Proxmox
- Pueue
- PulseAudio
- Puppet
- Quota
- Red Hat Satellite
- Restic
- Rsync
- Rtorrent
- Ruby
- Sabnzbd
- Sage
- Samba
- Screen
- Sed
- SELinux
- Sendmail
- Shell Configs
- Singularity
- Sleep
- Slurm
- SMART
- Sonarr
- Sqlite
- SquashFS
- Squid
- SSH
- Steam
- Stoken
- Strace
- Sudo
- Sync
- Sysctl
- Syslog
- Sysrq
- System Security Services Daemon (SSSD)
- Systemd
- Tar
- Tcsh
- Telegraf
- Terraform
- Thttpd
- Tmux
- Tomcat
- Top
- Umask
- Unix2dos
- Vim
- Virsh
- Virt-customize
- VirtualBox
- VirtualGL
- Visidata
- Vnstat
- Weechat
- Wget
- XFS
- Youtube-dl
- ZFS
- Zram
Package Management Linux Distributions Networking - Blazemeter
- CSF/LFD
- Exim
- Firewall
- FreeIPA
- Get DHCP Network Settings
- IP Aliasing
- Ipset
- IPTables
- IPv6
- IPXE
- Link Aggregation
- Linux Network Namespaces
- MTU
- Net-tools to iproute2
- Netcat
- Open vSwitch
- OpenWRT
- Postfix
- Raspberry Pi Torified Wifi
- Socat
- Static Routes
- StrongSwan
- Tcpdump
- Traffic Forwarder using IPTables
- Wi-Fi
- WireGuard
Containers