Bash Script to Write 2 Random Items to a File

Abstract: Selects two unique random items from a list and appends them to a file using Bash arrays without external dependencies.

Created: 2026-09-23 by

This Bash script selects two unique random items from a predefined list and appends them to a specified output file. By leveraging the built-in $RANDOM variable and array indexing, the solution ensures deterministic behavior without external dependencies, providing a robust method for generating randomized data entries in Linux environments.

Understanding Random Selection in Bash

Bash provides a built-in environment variable named $RANDOM that generates a pseudo-random integer between 0 and 32767 every time it is referenced. This feature eliminates the need for external commands like /dev/urandom or shuf for simple selection tasks. However, relying on global variables can introduce scope issues, particularly when functions are executed in subshells or pipelines. To create a reliable script, we must encapsulate the logic within functions that explicitly pass necessary data, avoiding reliance on implicit global state. The core challenge lies in selecting two distinct items. If we simply pick two random indices, there is a chance both selections will point to the same element. Therefore, the algorithm must verify uniqueness after each selection or remove the first selected item from the pool before making the second choice. Using Bash arrays allows us to treat the list of items as an indexed collection, making removal and re-indexing straightforward operations.

Constructing the Script Logic

To implement this correctly, we define a function that accepts the source list and the target file as arguments. This approach ensures that the function is portable and does not depend on hardcoded variable names. Inside the function, we convert the input string into an array. We then perform two iterations to select items. In the first iteration, we generate a random index based on the length of the current array. We store the item at that index and remove it from the array to guarantee the second selection is different. After collecting both unique items, we append them to the output file. It is crucial to handle file permissions correctly. If the user running the script does not have write access to the target directory, the operation will fail silently or throw an error depending on how the redirection is handled. We should include basic error checking to ensure the file exists or is created successfully. Here is the corrected implementation that avoids the global variable bug mentioned in previous drafts:
#!/bin/bash

# Function to write 2 random unique items to a file
write_random_items() {
    local source_list="$1"
    local output_file="$2"

    # Check if arguments are provided
    if [[ -z "$source_list" || -z "$output_file" ]]; then
        echo "Usage: $0 <list> <file>"
        return 1
    fi

    # Convert space-separated string to an array
    read -ra items <<< "$source_list"
    
    # Check if array has enough items
    if [[ ${#items[@]} -lt 2 ]]; then
        echo "Error: List must contain at least 2 items."
        return 1
    fi

    # Select first random item
    local idx1=$(( RANDOM % ${#items[@]} ))
    local item1="${items[$idx1]}"
    
    # Remove first item to ensure uniqueness
    unset 'items[idx1]'
    # Re-index the array to fill gaps
    items=( "${items[@]}" )

    # Select second random item from remaining
    local idx2=$(( RANDOM % ${#items[@]} ))
    local item2="${items[$idx2]}"

    # Append to file
    echo "$item1" >> "$output_file"
    echo "$item2" >> "$output_file"
    
    echo "Successfully wrote '$item1' and '$item2' to $output_file"
}

# Example usage
my_list="apple banana cherry date elderberry"
target_file="/tmp/random_output.txt"

write_random_items "$my_list" "$target_file"
This code snippet demonstrates best practices by using local variables within the function scope. The unset command combined with re-assignment items=( "${items[@]}" ) effectively shrinks the array, reducing the probability of duplicate selections to zero. This method is significantly more robust than trying to track used indices in a separate global array. For users interested in automating broader system tasks, such as integrating this randomness into deployment workflows, you might find our guide on Automating Deployments and Log Updates with Bash Script helpful. Combining random selection with log rotation or config generation can add variety to testing environments.

Handling Edge Cases and Permissions

While the core logic is sound, real-world execution requires attention to edge cases. What happens if the list contains only one item? The script checks for this condition and exits early with an informative message. This prevents undefined behavior where modulo arithmetic on a single-element array might behave unexpectedly in older Bash versions. Another common issue involves file paths. If the output_file path includes directories that do not exist, the >> operator will fail. It is advisable to use mkdir -p on the parent directory before writing, or check for the existence of the file's location. Additionally, if the script is run frequently, the file will grow indefinitely. For temporary data, consider using a temporary file in /tmp and cleaning it up afterward. If you are dealing with filenames that contain special characters or spaces, ensuring proper quoting around variables is essential. The example above uses double quotes around "$source_list" and "$output_file", which preserves whitespace and prevents word splitting issues. This is critical when the list items themselves contain spaces, such as "red apple" versus "red" and "apple". For those working with complex filename structures, understanding how to sanitize inputs is vital. You may want to explore Detox Filenames with bash Script in Kubuntu 22.04.4 LTS: A How-to Guide to learn how to handle problematic characters safely before passing them to scripts.

Frequently Asked Questions

How do I select random lines from an existing file instead of a hardcoded list?

You can replace the hardcoded list with a command substitution that reads the file. Use mapfile -t items <<(cat input.txt) to load lines into an array. Ensure the file does not contain empty lines if you require strict item counts, or filter them out using grep -v '^$'.

Is $RANDOM cryptographically secure for sensitive applications?

No, $RANDOM is not suitable for security-sensitive contexts like password generation or cryptographic keys. It is a pseudo-random number generator intended for general scripting purposes. For security needs, use /dev/urandom or tools like openssl rand.

What if I need more than two random items?

You can wrap the selection logic in a loop. Instead of hardcoding two selections, iterate N times. Each iteration should remove the previously selected item from the array to maintain uniqueness. Be careful not to exceed the total number of available items in the source list.

Why does my script sometimes produce duplicate items?

Duplicates usually occur if the removal step is skipped or if the array is not re-indexed after unsetting an element. Always reset the array indices using items=( "${items[@]}" ) after removing an element to ensure the next random index calculation remains valid against the new array length.

Can I use this script in a cron job?

Yes, but you must provide absolute paths for any files referenced in the script. Cron jobs run with a minimal environment and may not source your .bashrc or .profile. Ensure all variables, including the list content and file paths, are defined within the script itself.

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