Friday, August 1, 2025

Passing Values into Shell Scripts: A Beginner’s Guide with Examples

Shell scripting is a powerful tool for automating repetitive tasks in Linux. One of the key aspects of writing flexible and reusable shell scripts is the ability to pass input values into the script in various ways. Whether you're accepting command-line arguments, reading user input, or sourcing data from a file, shell scripting offers multiple mechanisms to handle data efficiently. These techniques are essential for writing scripts that can be reused in different scenarios—from system automation and cron jobs to configuration management and interactive tools.

In this post, we’ll explore five different ways to pass values into a shell script, using a common use case:

Use Case: Accept a value x and print it.

1. Hardcoded value 
In this method, the value is fixed directly in the script. This is simple but not suitable for reusable scripts.

Example:
#!/bin/bash
x=10
echo "Value of x is $x"

Best for: 
 Quick testing and debugging
 one-time-use scripts


2. Get the values from the user 
This method prompts the user for input at runtime using the read command.

Example: 

#!/bin/bash
# Method 2: Get input from user
read -p "Enter the value of x: " x
echo "Value of x is $x"

 Best for: Interactive scripts requiring user input.

3. Command-Line Arguments (Positional Parameters)
This method reads input from command-line arguments. The first argument is stored in $1, the second in $2, and so on.

#!/bin/bash
# Method 3: Use positional parameter
if [ -z "$1" ]; then
    echo "Usage: $0 <x>"
    exit 1
fi

x=$1
echo "Value of x is $x"

Run as: ./script.sh 10

Best for: Scheduled jobs or automation scripts.

4. read the values from the file 
This method reads the input from a file. It’s especially useful for batch processing.

#!/bin/bash
# Method 4: Read from file
file="input.txt"

if [ ! -f "$file" ]; then
    echo "Input file not found!"
    exit 1
fi

read -r x < "$file"
echo "Value of x is $x"

Best for: Reading config values or input data in bulk.



5. using flags or Named arguments 
For professional scripts or tools, you can use named arguments like -x to accept values using getopts.

#!/bin/bash
# Method 5: Use named flag with getopts

while getopts x: flag; do
  case "${flag}" in
    x) x=${OPTARG};;
    *) echo "Usage: $0 -x <value>"; exit 1;;
  esac
done

if [ -z "$x" ]; then
    echo "Usage: $0 -x <value>"
    exit 1
fi

echo "Value of x is $x"

# Run this script as:
./script.sh 10

 Best for: CLI tools with multiple named inputs.


Conclusion 

Choosing the right method to pass values into your shell script depends on your use case. For scripts requiring automation and integration, command-line arguments and flags are preferred. For interactive scripts, use read. For batch jobs, file input is efficient.


| Method                 | Best Use Case                                |
| ---------------------  | ---------------------------------------- |
| In Code                 | Quick testing                                 |
| `read`                    | Interactive input                            |
| Positional Params | Standard CLI usage                      |
| File Input              | Batch processing                           |
| Flags (`getopts`)   | Reusable tools with flexible input |

Friday, November 29, 2024

Basic Man Page Navigation

 

Basic Man Page Navigation

Navigating a man page can be straightforward and efficient with these keyboard shortcuts. Here's a quick reference to help you move through the content:


Exiting the Man Page

  • q: Quit and return to the terminal.

Scrolling Through the Content

  • Space: Move down one full page.
  • b: Move up one full page.

Jumping to Specific Positions

  • g: Jump to the top of the manual.
  • G: Jump to the bottom of the manual.

Moving Line by Line

  • j: Move forward one line.
    • With numbers: Specify the number of lines to move forward (e.g., 6j moves six lines ahead).
  • k: Move backward one line.
    • With numbers: Specify the number of lines to move backward (e.g., 3k moves three lines back).

Navigating by Windows

  • z: Scroll forward one window.
  • w: Scroll backward one window.
  • d: Move forward by half a window.
  • u: Move backward by half a window.

Searching for Keywords

  • /keyword: Search forward for a specific term.
  • n: Jump to the next search result.
  • N: Jump to the previous search result.
  • ?keyword: Search backward for a specific term.

Accessing the Help Menu

  • h: Display the help menu for all navigation commands.

These shortcuts simplify the process of exploring man pages, ensuring you can quickly locate the information you need. Incorporate them into your workflow to master man page navigation!

Thursday, November 28, 2024

The Power of man: Unlocking the Secrets of Linux Documentation

 The man command in Linux is used to display the manual (or documentation) of any command that can be run in the terminal. It provides detailed information about the command, including its NAME, SYNOPSIS, DESCRIPTION, OPTIONS, and more.

Sections of a Man Page:

A typical man page is divided into the following sections:

  1. NAME: Provides the command's name and a brief description.
  2. SYNOPSIS: Describes the command's syntax.
  3. DESCRIPTION: Offers a detailed explanation of the command's functionality.
  4. OPTIONS: Lists the available command-line options and their descriptions.
  5. EXIT STATUS: Explains the exit codes returned by the command.
  6. RETURN VALUES: Describes the values returned by the command (if applicable).
  7. ERRORS: Details potential error messages.
  8. FILES: Lists related files used or modified by the command.
  9. VERSIONS: Mentions the versions of the software.
  10. EXAMPLES: Provides examples of how to use the command.
  11. AUTHORS: Gives credit to the developers.
  12. SEE ALSO: Points to related commands or topics for further reading.

Syntax of the man Command:

The general syntax for the man command is:

man [OPTION] [SECTION] COMMAND

Common Usages:

  1. To display the entire manual of a command:


    man [COMMAND_NAME]

    Example:


    man ls
  2. To display a specific section of a manual:


    man [SECTION] [COMMAND_NAME]

    Example:


    man 1 ls
  3. To search for commands related to a keyword:


    man -k [KEYWORD]

    Example:

    man -k copy

Why Section Numbers are Important:

Linux manual pages are categorized into numbered sections to organize information. This is crucial because some commands, functions, or files share the same name but serve different purposes. By specifying a section number, you can access the exact information you need.

Common Section Numbers:

SectionDescription
1Executable programs or shell commands
2System calls (functions provided by the kernel)
3Library calls (functions in programming libraries)
4Special files (e.g., device files in /dev)
5File formats and conventions (e.g., /etc/passwd)
6Games and entertainment programs
7Miscellaneous topics (e.g., regex, ascii)
8System administration commands (usually requiring root privileges)
9Kernel routines (non-standard)

Examples of Using Section Numbers:

  1. To learn about the passwd command:


    man 1 passwd

    This shows the command used to change a user's password.

  2. To learn about the /etc/passwd file:


    man 5 passwd
  3. To learn about the printf command in the shell:


    man printf
  4. To learn about the printf function in C programming:


    man 3 printf
  5. To learn about system calls like open:


    man 2 open
  6. To learn about special files like /dev/null:


    man 4 null
  7. To explore games available on the system:


    man 6 tetris
  8. To discover system administration commands like sudo:


    man 8 sudo
  9. To explore miscellaneous topics like regular expressions or ASCII:


    man 7 regex man 7 ascii

Additional Useful Options for man:

  1. Display a concise one-line description of a command:


    man -f [COMMAND]

    Example:


    man -f ls

    Alternative:


    whatis ls
  2. Search for manual pages containing a keyword:


    man -k [KEYWORD]

    Example:


    man -k network

    Alternative:


    apropos network
  3. Find the location of a manual page:


    man -w [COMMAND]

    Example:


    man -w ls

Why Learn the man Command?

The man command is an indispensable tool for Linux users, offering:

  • Comprehensive Documentation: Access detailed information about commands, system calls, and configuration files.
  • Problem-Solving: Quickly understand syntax, options, and troubleshooting methods.
  • Self-Sufficiency: Gain the skills to explore and use any Linux feature effectively.

By mastering man, you can confidently navigate and utilize the full potential of Linux!

Tuesday, November 26, 2024

Mastering Linux Command Help: Your Guide to Getting Assistance with Linux Commands

 

Mastering Linux Command Help: Your Guide to Getting Assistance with Linux Commands

Linux is a powerful operating system widely known for its flexibility and robustness, enabling users to perform a vast array of tasks, from managing files to configuring servers. At the heart of Linux lies the command-line interface (CLI), a tool that provides unparalleled control and efficiency.

However, the CLI can appear daunting to beginners due to the sheer number of commands and their extensive options. This is where help commands come into play. They act as built-in guides, empowering users to explore and understand the capabilities of Linux commands without the need for external references.

In this post, we’ll outline essential commands that help you quickly access and leverage help features in the Linux environment. Whether you're a beginner or a seasoned sysadmin, knowing how to get help is key to navigating and mastering the Linux environment.

Different Methods to Get Help in Linux

You can access help through two primary sources:

  1. Command Line Help: Built-in tools that come with the system.
  2. External Resources: Online tools and websites to provide additional assistance.

Command Line Help

  1. View the Manual for a Particular Command

    • Commandman command_name
    • Use Case: Displays detailed documentation for a command.
      Example
      man ls
  2. Get More Information About a Command

    • Commandinfo command_name
    • Alternatepinfo command_name (colored output)
    • Use Case: For a more comprehensive, sometimes hyperlinked guide.
      Example:
      info ls
  3. Check if the Command is Internal or External

    • Commandtype command_name
    • Use Case: This helps identify whether a command is built into the shell or an external program.
      Example:
      type ls
  4. Check the Manual Page for Internal Commands

    • Commandhelp command_name
    • Use Case: For shell-built-in commands like cdecho, etc.
      Example:
      help cd
  5. List Commands Based on a Keyword

    • Commandapropos keyword or man -k keyword
    • Use Case: Finds commands and man pages related to a keyword.
      Example:
      apropos copy
  6. One-Line Description of a Command

    • Commandwhatis command_name or man -f command_name
    • Use Case: Provides a brief summary of the command.
      Example:
      whatis ls
  7. Locate the Path of a Command

    • Commandwhich command_name
    • Use Case: Shows the location of an executable command.
      Example:
      which ls
  8. Find the Path of Source, Binary, or Manual File

    • Commandwhereis command_name
    • Use Case: Locates the binary, source, and manual files related to a command.
      Example:
      whereis ls
  9. Get Cheat Sheets for a Command

    • Commandcheat command_name
    • Use Case: For quick reference to commands and their usage. (Requires installation of the cheat tool)
      Example:
      cheat ls
  10. Display the Help Module of a Command

    • Commandcommand_name --help or command_name -h
    • Use Case: Provides a summary of a command's options and usage.
      Example:
      ls --help
  11. Check the Version of a Command

    • Commandcommand_name --version or command_name -V
    • Use Case: Shows the version of the command.
      Example:
      ls --version
  12. Generate a List of Possible Command Completions

    • Commandcompgen -c
    • Use Case: List all available commands.
      Example:
      compgen -c
  13. List All Environment Variables

    • Commandenv or set | less
    • Use Case: Displays environment variables.
      Example:
      env
  14. Check if a tool is Installed

    • Commandcommand -v command_name(tool)
    • Use Case: Verifies if a command is installed on the system.
      Example:
      command -v ls
  15. View Simplified Command Examples (TLDR - Too Long Didn’t Read)

    • Commandtldr command_name (requires tldr tool)
    • Use Case: Provides simplified examples and usage for commands.
      Example:
      tldr ls

External Resources

  1. ExplainShell

    • An interactive website that breaks down shell commands and explains each part in plain English. It's especially useful for understanding complex command line syntax.
  2. TLDR Pages In-Browser

    • An online version of the TLDR pages, which offers simplified command usage and examples directly in your browser.
      3. cheat.sh 
                https://cheat.sh/

      4. man7.org 
                 Online searchable Linux man pages 

Conclusion

Mastering Linux commands involves understanding not only how to execute them but also how to get help when you're unsure. With the help commands outlined above, you can easily access built-in resources, documentation, and external tools that will guide you through the learning process. Whether you’re troubleshooting or learning a new command, these help features will ensure you’re never stuck for long.

Feel free to explore these commands, and let us know if there are any others you find useful in your Linux journey!

Passing Values into Shell Scripts: A Beginner’s Guide with Examples

Shell scripting is a powerful tool for automating repetitive tasks in Linux. One of the key aspects of writing flexible and reusable shell s...