Pustakam Library

Free Technology learning guide

Linux Command Line and Bash Scripting for Beginners

Linux Command Line and Bash Scripting for Beginners — a free beginner-level guide covering linux command line bash scripting basics. Learn with clear...

111 min read12 chaptersbeginner

What you will learn

  1. Introduction to the Linux Command Line
  2. Basic File and Directory Operations
  3. Working with Text Files and Pipes
  4. Introduction to Bash Scripting
  5. Control Structures in Bash
  6. Functions and Modular Scripting
  7. Error Handling and Debugging
  8. Working with Environment Variables
  9. Process Management and Job Control
  10. Package Management and System Updates
  11. Networking Basics from the Command Line
  12. Cron Jobs and Scheduled Tasks

1. Introduction to the Linux Command Line

Why the Command Line Matters Imagine you’re troubleshooting a server that has stopped serving a web page. The graphical desktop environment is frozen, the mouse doesn’t move, and you only have a blinking cursor on a black screen. With a single line of text you can: 1. Check whether the web server process is running 2. Read the last entries of the log file 3. Restart the service All without touching a mouse, without opening a graphical tool, and without waiting for a slow desktop to load. This is the power of the Linux command line: a text‑only interface that lets you ask the operating system exactly what you need, when you need it. For beginners, the command line can feel intimidating—cryptic commands, strange symbols, and a sea of unfamiliar words. Yet, learning just a handful of commands unlocks a world where you can explore, diagnose, and automate tasks with speed and precision. This chapter will give you the foundation you need to start using the command line confidently. --- What the Linux Command Line Is - Terminal – The window (or virtual console) that displays a text prompt and accepts your typed input. It is the "screen" where you interact with the command line. - Shell – The program that interprets what you type and runs the appropriate system commands. The most common shell on modern Linux distributions is Bash (Bourne‑Again SHell), but others exist (e.g., zsh, fish). - Prompt – The short string that appears before each command you type, often something like user@host:~$. It tells you that the shell is ready to receive input. When you type a line of text and press Enter, the shell parses the line, looks for the requested command, runs it, and then returns control to you with a new prompt. This cycle repeats as long as the terminal session is open. Why Use the Command Line? | Benefit | Typical Scenario | |--------|------------------| | Speed | Navigating to a directory with cd /var/log is faster than clicking through a file manager. | | Remote Access | Over SSH you can manage a server that has no graphical desktop at all. | | Automation | Scripts can chain many commands together to perform repetitive tasks automatically. | | Precision | Commands let you specify exact options (e.g., ls -l --color=auto) that GUI tools may hide. | | Low Resource Usage | A terminal consumes a few megabytes of RAM, while a full desktop environment can require hundreds. | Even if you never write a script, mastering the command line gives you a reliable toolbox for everyday tasks and for the more advanced topics that follow in later modules. --- The Anatomy of …

2. Basic File and Directory Operations

1. A Real‑World Prompt: “Where did my report go?” You’ve just finished a draft of the quarterly report and saved it as report.txt in your home directory. A teammate asks you to send the file to the shared project folder, but you’re not sure whether the file is still there, what its current name is, or who can read it. Answering those questions requires three basic skills: Finding the file and looking at its contents. Moving or renaming it to the correct location. Checking that the right people have permission to read it. All of those actions are performed with a handful of Linux commands that you will master in this chapter. --- 2. Creating Files and Directories 2.1 The touch command | Syntax | Description | |--------|-------------| | touch filename | Creates an empty file called filename if it does not already exist. | | touch existingfile | Updates the file’s timestamp (the “last‑modified” time) to the current moment. | Why “touch”? The command mimics the act of “touching” a file: if the file is absent, it is created; if it exists, its timestamp is “touched”. Example – creating a new report Run ls -l to see the new file: The size is 0 because the file is empty. 2.2 Making directories with mkdir | Syntax | Description | |--------|-------------| | mkdir dirname | Creates a new directory named dirname. | | mkdir -p /path/to/dir | Creates the whole path, creating any missing parent directories. | Example – a project folder Now project/shared/docs exists, even though none of the parent directories were present before. 2.3 Quick sanity check: ls ls – list contents of the current directory. ls -l – long format shows permissions, owner, size, and timestamps. ls /absolute/path – list a directory using an absolute path (starts with /). ls relative/path – list using a relative path (relative to the current directory). --- 3. Naming, Moving, and Copying 3.1 Renaming with mv The move command (mv) does two jobs: 1. Rename a file or directory within the same location. 2. Move it to a different directory. | Syntax | Example | Effect | |--------|---------|--------| | mv oldname newname | mv report.txt finalreport.txt | Renames the file. | | mv file /path/to/dir/ | mv finalreport.txt project/shared/docs/ | Moves the file into the target directory. | | mv dir1 dir2 | mv project oldproject | Renames a directory. | Tip: If the destination already contains a file with the same name, mv overwrites it without warning. Use -i (interactive) to be prompted before overwriting: 3.2 Copying with cp cp creates a duplicate of a file or directory. By default it copies only files; to copy directories you need the …

3. Working with Text Files and Pipes

A Real‑World Problem: Finding the Culprit in a Log File Imagine you are the administrator of a small web server. Every night the server writes a file called access.log that records every request it receives. One morning you notice that the site is unusually slow. You suspect that a particular client IP address is hammering the server with requests, but the file is 10 MB long—scrolling through it with a text editor is impossible. How can you, using only the command line, quickly answer these questions? Which lines contain the word error? What client IP addresses appear most often? Can you create a short report that you can email to a colleague? The tools you need—grep, awk, sed, and the pipe operator |—are the focus of this chapter. By the end, you’ll be able to build pipelines that turn raw text into useful information, and you’ll know how to save that output with redirection operators and . --- 1. Text Files – The Building Blocks A text file is simply a sequence of characters stored on disk, with each line terminated by a newline character (\n). Unlike binary files, a text file can be opened and read by any program that understands plain text. Most configuration files, logs, and source‑code files you’ll encounter are plain text. Key points for beginners: | Term | Meaning | |------|----------| | Line | A row of characters ending with a newline. | | Field | A piece of data within a line, often separated by spaces or tabs. | | Delimiter | The character that separates fields (e.g., space, comma, :). | Because text files are human‑readable, they are perfect for quick inspection with commands like cat, head, and tail, and they are the natural input for the three utilities we will explore. --- 2. Searching with grep grep (global regular expression print) scans a file (or standard input) and prints only the lines that match a pattern. A pattern can be a simple word or a more complex regular expression (regex). 2.1 Basic Syntax PATTERN – the text or regex you are looking for. FILE – one or more files to search; if omitted, grep reads from standard input (the data stream coming from the previous command or the keyboard). 2.2 First Examples 2.3 Common Options | Option | What it does | |--------|--------------| | -i | Ignore case (makes the search case‑insensitive). | | -v | Invert match – show lines that do not contain the pattern. | | -c | Count matching lines instead of printing them. | | -A n | Print n lines after each match (useful for context). | | -B n | Print n lines before each …

4. Introduction to Bash Scripting

A Real‑World Problem: Automating a Daily Report Imagine you are the new assistant for a small team that runs a nightly backup of a shared folder. Every evening you must: 1. Check that the backup directory exists. 2. Count how many files were copied. 3. Email a short summary to the team. You could type the same series of commands every night, but that is slow, error‑prone, and defeats the purpose of using the command line for automation. A tiny Bash script can do the whole job in a few seconds, and you’ll learn three core skills while building it: Adding a shebang line so the system knows which interpreter to use. Declaring variables and reading user input. Setting execute permissions with chmod +x. Below we walk through each step, explaining the why as well as the how. --- 1. Creating Your First Bash Script 1.1 Choose a Descriptive Name Pick a name that reflects the script’s purpose. For our backup report we’ll call it dailyreport.sh. The .sh suffix is not required, but it signals to other users (and yourself) that the file contains a shell script. 1.2 Add the Shebang Line The shebang (!) is the very first line of a script. It tells the kernel which interpreter to launch when the file is executed. For Bash scripts we use: Using /usr/bin/env makes the script portable: it looks up the bash binary in the user’s PATH, which works on most Linux distributions. Open dailyreport.sh with your favorite editor (e.g., nano, vim, or code) and type the line: Save and close the file. At this point the script still isn’t executable, but we have a proper starting point. 1.3 Write a Minimal “Hello, World!” Example Before we add the backup logic, let’s verify that the script runs: Run the script without making it executable to see the effect of the shebang: If this prints correctly, the shebang is functional. --- 2. Making the Script Executable Linux respects file permissions to decide who can read, write, or execute a file. By default, new files are created with read/write permissions only (rw-). To run a script directly (e.g., ./dailyreport.sh) you must add the execute flag. The +x adds execute permission for the file owner, the group, and everyone else. Now you can launch the script just by typing its path: Tip: When you see a “Permission denied” error, double‑check that you used chmod +x on the correct file. --- 3. Introducing Variables Variables let you store data—strings, numbers, paths—and reuse them throughout the script. In Bash, you assign a value without spaces around the = sign, and you reference it with a leading $. 3.1 Simple Variable Assignment When you run this …

5. Control Structures in Bash

Making Decisions: if, elif, and else When a script runs, it often has to choose what to do next based on the state of the system or on information supplied by the user. Imagine you are writing a small utility that backs up a directory only if there is enough free space on the disk. The script must: 1. Find out how much free space exists. 2. Compare that number with a threshold you set (e.g., “at least 500 MB”). 3. Either run the backup command or print a warning and exit. That “choose one path or the other” logic is exactly what Bash’s conditional statements provide. The Basic Syntax [ and ] – These are actually the test command; they evaluate an expression and return a status code (0 = true, non‑zero = false). then – Marks the start of the block that runs when the test succeeds. elif – Short for “else if”; allows you to chain additional tests. else – Optional; runs when all previous tests fail. fi – The word “if” backwards; it closes the conditional block. Tip: In Bash, you can also write the test using [[ … ]], which offers more features (e.g., pattern matching) and reduces quoting headaches. For beginners, [ works fine and matches what you already saw when testing file existence in earlier chapters. Common Test Operators | Category | Operator | Example | Meaning | |----------|----------|---------|---------| | File tests | -e | [ -e /etc/passwd ] | True if the file exists | | | -d | [ -d /var/log ] | True if it is a directory | | | -f | [ -f script.sh ] | True if it is a regular file | | String tests | = | [ "$name" = "admin" ] | Equality (case‑sensitive) | | | != | [ "$mode" != "debug" ] | Inequality | | | -z | [ -z "$var" ] | True if the string is empty | | Numeric tests | -eq | [ "$size" -eq 1024 ] | Equal (integer) | | | -lt | [ "$age" -lt 18 ] | Less than | | | -gt | [ "$count" -gt 5 ] | Greater than | Remember: All arguments inside [ … ] are separate words; therefore you must space the brackets from the condition and quote variables ("$var") to protect against spaces or empty values. A Worked‑Through Example The script uses df to query free disk space, strips whitespace with tr, and stores the number in FREE. The first if checks whether the free space meets the full threshold (-ge = “greater or equal”). The elif provides a middle ground: if at least half the …

6. Functions and Modular Scripting

A Real‑World Prompt: “One Script to Rule Them All” Imagine you are the on‑call engineer for a small web server. Every morning you need to: 1. Check that the web service is running. 2. Back up the /var/www/html directory. 3. Rotate the logs in /var/log/nginx. 4. Send a short status email to the team. You could write a single long script that runs each of these steps one after another. The script works—until tomorrow, when the log‑rotation policy changes and you have to tweak the path, or when a colleague asks you to reuse the backup routine on a different server. Every tiny change forces you to edit the whole file, increasing the chance of breaking something else. The solution? Break the script into reusable functions and keep the “glue” code minimal. Functions let you encapsulate a task, give it a clear name, and call it whenever you need it—exactly the kind of modularity that makes scripts maintainable, testable, and easy to share. Below we’ll explore how to define, call, and compose functions in Bash, how to pass data in and out, and how to organize a script into tidy, reusable pieces. --- 1. What Is a Function, Anyway? In Bash a function is a named block of commands that you can invoke from anywhere in the script (or from the command line). Think of it as a mini‑program inside your script. When the shell reaches a function call, it temporarily jumps to the function’s body, runs the commands, then returns to the next line after the call. A function does not automatically run when the script starts; it only runs when you explicitly call it. This separation of definition and execution is the cornerstone of modular scripting. 1.1 Basic Syntax There are two equivalent ways to declare a function: Both definitions create a function called greet. The body is enclosed in braces { … }. Whitespace is flexible, but a newline or semicolon after the closing brace is required. Tip: Use the style that matches the conventions of the project you’re working on. The second style (name() { … }) is more common in portable scripts. 1.2 Where Functions Live A function definition can appear anywhere in the script—at the top, middle, or bottom—provided it is defined before the first call. Bash reads the entire file before executing, so you can place the definitions at the top for readability and keep the “main” logic at the bottom. --- 2. Calling Functions Once a function exists, you invoke it just like any other command: The shell substitutes the function for a command, runs its body, then continues with the next line. Because functions obey the same quoting rules as commands, …

7. Error Handling and Debugging

A Script That Went Wrong – and How It Could Have Been Saved Imagine you are automating a nightly backup of a critical configuration directory: You run the script, glance at the prompt, and go to sleep. At 02:00 AM the backup server crashes. When the system boots again, the /backup directory is present, but the myapp sub‑directory is empty. Why? The cp command failed because the source filesystem was read‑only, but the script kept running silently and exited with a success status. A tiny oversight turned a routine job into a data‑loss incident. By adding proper error handling and debugging steps, the same script could have stopped immediately, logged the problem, and left a clear trace for you to investigate. The rest of this chapter shows exactly how to do that, using only Bash built‑ins that you already use for writing scripts. --- 1. When a Command Fails – What Happens? Every command that runs in the shell returns an exit status (also called a return code). By convention: 0 means success. Any non‑zero value signals failure. The specific number can give clues (e.g., 1 for a generic error, 2 for misuse of shell built‑ins, 127 for “command not found”, etc.). If you have never inspected $? (the variable that holds the most recent exit status), try this simple test: When a script finishes, the shell automatically returns the exit status of the last command that ran. If a command fails early but later commands succeed, the script may still exit with 0, misleading anyone who relies on its result. --- 2. Making the Shell Stop on Errors Bash provides three options that turn “quiet failures” into immediate aborts: | Option | Effect | Typical Use | |--------|--------|-------------| | set -e | Exit the script as soon as any command returns a non‑zero status. | Prevents hidden failures in long pipelines. | | set -u | Treat unset variables as an error and abort. | Catches typos like $filname instead of $filename. | | set -o pipefail (optional) | Makes a pipeline fail if any component fails, not just the last one. | Useful when you combine commands with |. | Note – set -e does not trigger on every possible failure (e.g., in conditionals). The rules are a bit subtle, but for beginners the safest pattern is to combine it with explicit checks where needed. 2.1 Adding set -e and set -u to the Backup Script Now, if cp cannot read the source, the script stops immediately, and you see the error message printed by cp. Because set -u is active, a typo such as srcdir="/etc/myapp" → srcdi="/etc/myapp" would cause the script to abort before any file operations …

8. Working with Environment Variables

A Real‑World Prompt: “Why is my script still using the old database password?” You sit down at the terminal, open a Bash script that deploys a web service, and notice that after you edited the password in a configuration file the script keeps printing the previous value. A quick echo $DBPASSWORD shows the new password, but the script still uses the old one. The culprit? The script is reading a local variable that was never updated from the environment variable you changed. Understanding how Bash distinguishes between local (shell‑only) variables and environment variables that are inherited by child processes is the key to writing reliable, configurable scripts. --- 1. Local vs. Environment Variables | | Scope | Visible to child processes? | Typical creation syntax | |---------------------|----------------------------------------|---------------------------------|-----------------------------| | Local variable | Only the current shell (or function) | No | var=value | | Environment variable | Current shell and any program launched from it | Yes | export VAR=value (or VAR=value then export VAR) | Local variable – lives only in the shell where it was defined. When you run another command (e.g., ls, python script.py), that command cannot see the variable unless you explicitly export it. Environment variable – part of the process’s environment. When the shell forks a new process, the environment is copied, so the child can read the variable. Why it matters – Most configuration data that a script wants to share with the programs it calls (database credentials, path settings, locale options) should be stored in environment variables. This lets you change a value in one place and have every subsequent command automatically pick it up. --- 2. Creating and Exporting Environment Variables 2.1 One‑off export The variable DBPASSWORD is now part of the environment for the current shell session and any child processes started from here. 2.2 Exporting an existing local variable 2.3 Setting and exporting in a single line Both forms are equivalent; choose the style that keeps your scripts readable. 2.4 Making exports persistent If you need a variable every time you log in, add the export line to one of your shell start‑up files: ~/.bashrc – executed for interactive non‑login shells. ~/.profile or ~/.bashprofile – executed for login shells. Tip – Keep start‑up files tidy; group related exports together and comment why each variable exists. --- 3. Viewing and Unsetting Environment Variables 3.1 List all environment variables Both commands dump the current environment, one variable per line. 3.2 Show a single variable Remember to quote the expansion to preserve whitespace or special characters. 3.3 Unset (remove) a variable unset works for both local and environment variables. After unsetting, the variable disappears from the environment of subsequent commands. 3.4 Temporarily overriding a …

9. Process Management and Job Control

Seeing the World of Processes When you open a terminal you are not just looking at a blank screen – you are looking at a process that the kernel created for you. Every program that runs, from ls to a full‑blown graphical editor, lives as a process. The kernel assigns each process a unique process identifier (PID) and keeps track of its parent‑child relationships, resource usage, and state. What a PID Looks Like In the example above, 2745 is the PID of the Bash instance you are interacting with. Knowing a PID lets you ask the system for details about that specific process. The ps Command – Your First Process Inspector The simplest way to list processes is with ps. By default it shows only the processes attached to your terminal: Add options to see more: | Option | What it does | |--------|--------------| | -e or -A | Show all processes on the system | | -f | Full‑format listing (PPID, UID, start time, etc.) | | -l | Long format, includes scheduling priority | | -u <user | Show processes belonging to a specific user | A common combination for beginners is ps -ef: The columns you’ll see most often are: PID – the process identifier. PPID – the parent PID (the process that launched this one). UID – the user that owns the process. CMD – the command that started the process, including any arguments. If you prefer a live, updating view, tools like top or htop (if installed) give you a continuously refreshed list with CPU and memory percentages. They are not required for the basics, but they are handy for quick monitoring. --- Controlling Processes with Signals A running process can be signaled to change its behavior. Signals are small integer codes the kernel sends to a process; the process can ignore, handle, or terminate on receipt of a signal. The Most Common Signals | Signal | Number | Typical use | |--------|--------|-------------| | SIGTERM | 15 | Politely ask a process to quit (default for kill). | | SIGKILL | 9 | Forceful termination; cannot be ignored. | | SIGINT | 2 | Interrupt (what Ctrl‑C sends). | | SIGSTOP | 19 | Pause a process (what Ctrl‑Z sends). | | SIGCONT | 18 | Resume a paused process. | Using kill The kill command simply sends a signal to a PID. By default it sends SIGTERM: If the process refuses to stop, you can be more aggressive: You can also specify the signal by name: Killing by Name – killall and pkill When you don’t know the exact PID, killall (or pkill) can target processes by their command name: Tip: pkill supports pattern …

10. Package Management and System Updates

A Real‑World Prompt: “My Server Is Out‑of‑Date—What Now?” You have just finished provisioning a fresh Ubuntu 20.04 virtual machine. The base install works, you can log in, and the prompt greets you. The next step in your checklist is to install a web server, but before you do that you notice a warning: You could manually download each .deb file from a website, copy it to the server, and run dpkg -i …. That would be tedious, error‑prone, and would ignore the many dependencies (other packages that a piece of software needs to run). The Linux command line has a built‑in solution: package managers. Whether you are on Ubuntu, CentOS, or Fedora, a single command can fetch, verify, install, update, or remove software while handling dependencies automatically. In the sections that follow we will explore the three most common package managers—apt, yum, and dnf—and see how to keep a system healthy with updates and repository management. All commands assume you are working from the shell you have already learned to navigate, and that you will use sudo when a command requires administrative privileges. --- 1. Package Management Fundamentals 1.1 What Is a Package? A package is a bundled archive that contains a program’s files (executables, libraries, configuration files) together with metadata describing: Version – e.g., nginx 1.18.0-0ubuntu1 Dependencies – other packages that must be present for this one to work Provides/Conflicts – virtual packages or incompatibilities Source – where the package originated (repository) The package manager reads this metadata and ensures that all required pieces are present before installing anything. 1.2 Repositories: Where Packages Live A repository (or repo) is a server that hosts collections of packages. Repositories are indexed so that a client can quickly ask, “What versions of nginx are available?” The index is stored locally on your machine and refreshed with a command such as apt update. Typical repository locations: | Distribution | Default Package Manager | Default Repo Directory | |--------------|--------------------------|------------------------| | Debian/Ubuntu | apt (or apt-get) | /etc/apt/sources.list and /etc/apt/sources.list.d/ | | RHEL/CentOS 7 | yum | /etc/yum.repos.d/ | | RHEL/CentOS 8+, Fedora | dnf | /etc/yum.repos.d/ (same layout) | 1.3 Options, Arguments, and the Role of sudo All three managers follow the same command‑line pattern you have already seen: Options (also called flags) modify the behavior of the command, e.g., -y to answer “yes” automatically. Arguments are the items the command acts upon, such as the name of a package. Because installing, updating, or removing software touches system directories, you must run these commands with superuser privileges. The most common way is to prefix the command with sudo, which you already used in earlier chapters. --- 2. Installing Packages 2.1 The Basic Install Command …

11. Networking Basics from the Command Line

A Real‑World Problem: “Why Can’t I Reach My Remote Server?” You’ve just been asked to pull the latest log files from a web server in another city. You type ssh user@remote.example.com and get: Before you start rewriting firewalls or reinstalling software, you need to prove where the breakdown is happening. Is the remote host down? Is your own network mis‑configured? Is there a broken hop somewhere in between? The command‑line tools covered in this chapter give you a systematic, repeatable way to answer those questions, inspect your own network interfaces, and move files securely— all without leaving the terminal you already know how to use. --- 1. Checking Network Connectivity 1.1 ping: The Quick “Is It Alive?” Test ping sends ICMP Echo Request packets to a target host and reports how long each reply takes. Basic syntax | Option | Meaning (first time) | |--------|----------------------| | -c | Stop after sending count packets (useful for scripts) | | -i | Seconds to wait between packets (default 1 s) | | -W | Seconds to wait for each reply before timing out | Example – Test connectivity to 8.8.8.8 (Google DNS) three times: Typical output: Key points to read: packet loss – If any packets are lost, the network is unreliable. time – Round‑trip latency; larger numbers may indicate congestion. ttl (time‑to‑live) – Decrements at each router; a very low value can hint at a long path. If you see “Destination Host Unreachable” or “Network is unreachable”, the problem is likely local (your NIC, router, or ISP). If the host never replies but you get no error, the remote side might be blocking ICMP. Tip: Some servers deliberately disable ICMP replies for security. In that case, ping will time out even though the server is reachable. Move on to the next tool. --- 1.2 traceroute: Mapping the Path traceroute (or tracepath on some minimal systems) shows each hop a packet traverses to reach its destination, revealing where delays or drops occur. Basic syntax | Option | Meaning | |--------|---------| | -I | Use ICMP Echo (default on most Linux) | | -T | Use TCP SYN packets (helpful when ICMP is filtered) | | -n | Show numeric IP addresses only (skip DNS lookups, faster) | | -w | Seconds to wait for each reply | Example – Trace the route to remote.example.com without DNS lookups: Sample output (abbreviated): Interpretation: Each line = one hop (router) identified by its IP. indicates no reply within the timeout – a possible firewall or overloaded router. The latency (e.g., 12.8 ms) is the round‑trip time to that hop. If the trace stops early (many consecutive ), the problem likely lies after the last responding …

12. Cron Jobs and Scheduled Tasks

A Day in the Life of an Automated Server Imagine you are responsible for a modest web server that hosts a personal blog. Every night at 02:00 AM the server should: 1. Compress the previous day’s access logs. 2. Back up the compressed logs to a remote storage bucket. 3. Delete any log files older than 30 days. You could log in manually and run three separate commands, but what if you forget, travel, or the server reboots? A cron job ensures those steps happen automatically, every night, without any human intervention. In this chapter you will learn how to set up that reliability, understand the language that tells cron when to run a command, and discover the companion tool at for one‑off scheduling. --- 1. The Cron Daemon – Your Time‑Keeper cron is a daemon (a background service) that wakes up every minute, checks a set of tables called crontabs, and launches any commands whose schedule matches the current time. - System‑wide crontabs live in /etc/crontab and /etc/cron. directories. - User crontabs are private to each account and are edited with the crontab command. Because cron runs as a background process, you do not start it manually; it is started automatically by your init system (e.g., systemd). If you ever need to verify it is active, use: Note: The daemon inherits a minimal environment. If your scripts rely on environment variables (PATH, custom variables, etc.), you must set them explicitly inside the crontab or in the script itself—something you already explored in Working with Environment Variables. --- 2. Crontab Syntax – The Five‑Field Calendar A crontab line consists of six fields: | Field | Allowed values | Meaning | |-------|----------------|---------| | minute | 0‑59 | Minute of the hour | | hour | 0‑23 | Hour of the day (24‑hour clock) | | day‑of‑month | 1‑31 | Day of the month | | month | 1‑12 (or names) | Month of the year | | day‑of‑week | 0‑7 (0 or 7 = Sunday) | Day of the week | | command | any valid shell command | What to execute | Each field can contain: - A single number (5 → the 5th minute). - A range (1‑5 → minutes 1 through 5). - A list (0,30 → minute 0 and 30). - An asterisk () meaning “every possible value”. - Step values (/15 → every 15 minutes). Special Strings Cron also understands a handful of nicknames that replace the five time fields: | String | Equivalent Schedule | |--------|---------------------| | @reboot | Run once at system boot | | @yearly / @annually | 0 0 1 1 (midnight Jan 1) | | @monthly | 0 0 1 (midnight …

Continue learning