Bash AutoComplete: Custom Script Possibilities with a Text File

Abstract: Solve dynamic Bash auto-completion for custom scripts by reading options from a text file and registering the completion function.

Created: 2026-08-08 by
You can customize Bash auto-completion by defining a completion function that reads options from a text file and registers it with the complete command. This approach allows dynamic updates to available commands without modifying the script itself, provided the text file is properly formatted and the shell source configuration correctly.

Understanding Bash Completion Functions

Bash uses a specific mechanism called "completion functions" to determine what suggestions to offer when you press the Tab key. These functions are standard shell functions that return a list of possible completions via the COMPREPLY array variable. When you create a custom completion for a script or command, you are essentially writing a function that parses the current word being typed and suggests matches. For simple cases involving a static list of options stored in a file, this process becomes quite straightforward. The core requirement is that your function must populate COMPREPLY with an array of strings that match the user's input prefix.

Preparing the Text File

The foundation of this customization is the text file itself. It should contain one option per line, with no extra whitespace or special characters that might interfere with parsing. For example, if you are creating autocomplete for a deployment tool, your file might look like this:
deploy-staging
deploy-production
rollback-v1
rollback-v2
status-check
restart-service
Ensure the file is readable by the user running the shell. If the file is located in a non-standard directory, you must provide the full path in your script. It is also advisable to keep the file in a consistent location, such as ~/.config/myapp/options.txt, so that the completion script can reliably find it. Avoid using commas or other delimiters; line breaks are the standard separator for this method because they are easily handled by shell utilities like grep or while read loops.

Writing the Completion Function

The next step is to write the shell function that will act as the completion handler. This function needs to perform three main tasks: extract the current word being typed, filter the options from the text file based on that word, and assign the results to COMPREPLY. Here is a robust template for such a function:
my_custom_completion() {
    local cur="${COMP_WORDS[COMP_CWORD]}"
    local opts_file="$HOME/.config/myapp/options.txt"
    
    # Read all lines from the file into an array
    mapfile -t all_opts < "$opts_file"
    
    # Filter options that start with the current word
    COMPREPLY=($(compgen -W "${all_opts[*]}" -- "$cur"))
}
In this code, ${COMP_WORDS[COMP_CWORD]} retrieves the word currently being edited by the user. The mapfile command (also known as readarray) loads each line of the text file into the all_opts array. Finally, compgen -W generates completions from the word list that match the prefix $cur. This method is efficient because it leverages built-in Bash tools rather than spawning external processes for every keystroke.

Registering the Completion

Once the function is defined, it must be registered with Bash using the complete builtin. This tells Bash to call your function whenever the specified command is invoked. Assuming your script is named myapp, you would add the following line to your ~/.bashrc or ~/.profile:
complete -F my_custom_completion myapp
After adding this line, you need to reload your shell configuration by running source ~/.bashrc. From then on, typing myapp [Tab] will trigger your custom function. This registration step is critical; without it, Bash will not know to use your custom logic instead of default filename completion. Note that if you change the text file while the shell is active, you do not need to re-source the config, as the function reads the file at runtime. However, changes to the function definition itself require a shell restart or re-sourcing.

Troubleshooting Common Issues

If your autocomplete does not work, check the permissions of the text file and ensure the path in the function is correct. A common mistake is forgetting to quote variables, which can cause word splitting issues if filenames contain spaces. Additionally, verify that the complete command is associated with the exact name of the executable. If you are testing this in a subshell or a different environment, ensure that the ~/.bashrc modifications have been applied. You can debug the function by calling my_custom_completion manually after setting COMP_WORDS and COMP_CWORD variables artificially, though this is rarely necessary for simple text-file-based completions. For more complex scenarios involving arguments, consider exploring how to handle flags and positional parameters separately.

Frequently Asked Questions

Can I use multiple text files for different categories?

Yes, you can modify the function to read from different files based on the context or arguments provided. You would simply add logic to check COMP_WORDS for specific flags and select the appropriate file path before filtering.

Does this work in Zsh or Fish shells?

No, this specific syntax relies on Bash-specific variables like COMP_WORDS and the complete builtin. Other shells have their own completion systems, such as Zsh's _arguments or Fish's declarative completions.

How do I handle options with spaces in them?

The compgen -W approach handles spaces correctly if the words are properly quoted in the array. Ensure that your text file does not introduce unintended word splitting by using mapfile which preserves line breaks exactly as they appear.

Can I make the completion case-insensitive?

By default, Bash completion is case-sensitive. To make it case-insensitive, you can set the shopt -s nocaseglob option in your shell configuration, or modify the completion function to convert both the input and the options to lowercase before comparison.

What happens if the text file is empty?

If the file is empty, the all_opts array will be empty, and compgen will return nothing. This means no suggestions will appear, which is the expected behavior. It is good practice to add a fallback message or default options in your function if the file might be missing.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More