Skip to content
The Chat Archive
claude-2.1· Anthropic Arena Human Preference 55K

exit shell script if argument contains anything but numbers and letters

  1. User

    exit shell script if argument contains anything but numbers and letters

  2. Assistant

    Here is how you can exit a shell script if the argument contains anything but numbers and letters:

    #!/bin/bash
    
    if [[ $1 =~ [^a-zA-Z0-9] ]]; then
      echo "Error: Argument contains invalid characters"
      exit 1
    fi
    
    # rest of script code goes here
    

    Breakdown:

    • $1 refers to the first argument passed to the script
    • The =~ operator allows you to use regex matching on the right hand side
    • [^a-zA-Z0-9] matches any character that is not a letter or number
    • If this regex matches, it means the argument contains invalid chars
    • Print an error message and call exit 1 to quit the script

    So this will immediately quit the script if the first argument contains anything other than alphanumeric characters. You can expand the character class in the regex to allow other types of chars if needed.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.