7

I am trying to generate a random text file on my macbook from terminal. What I am trying is that:

tr -dc A-Za-z0-9 < /dev/urandom | head -c100 > RandomFile.txt

but im getting

tr: Illegal byte sequence

What am i doing wrong?

1
  • 1
    /dev/urandom delivers hex bytes in the range 00..ff. Start with hexdump /dev/urandom and check the manpage for hexdump's format options of it's output. Commented Nov 24, 2012 at 13:46

2 Answers 2

9

Set this environment variable and you should be good to go:

setenv LC_ALL C

The answer for which I found on this page.

And with that environment variable in place, I see a nicely formatted output:

tr -dc A-Za-z0-9 < /dev/urandom | head -c100
Kk4kfjR3O0UraMpfTGicGvYCziFClJQUTO3zCXdo05RTxEUigqPXTkjtiGOsTsaNyqNR3rX2dsmPlHkSdqO5qWBTmIFIYezsekWT[~]:;
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, the page is useful. it is actually export LC_ALL=C instead of setenv LC_ALL C
Yep. It depends on whatever shell your Terminal is using.
2
# Print or assign a random alphanumeric string of a given length.
# rndstr len [ var ]
function rndstr {
    if [[ $FUNCNAME == "${FUNCNAME[1]}" ]]; then
        unset -v a
        printf "$@"
    elif [[ $1 != +([[:digit:]]) ]]; then
        return 1
    elif (( ! $1 )); then
        return
    else
        typeset -a a=({a..z} {A..Z} {0..9})
        eval '${2:+"$FUNCNAME" -v} "${2:-printf}" -- %s "${a[RANDOM%'"${#a[@]}"']"{1..'"$1"'}"}"'
    fi
}

rndstr 100

This is my library function for this. The advantage is performance and the ability to assign to a variable directly. Might be overkill for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.